c# - winform - windows forms
如何在檢查文件是否存在後刪除文件 (6)
使用File類非常簡單。
if(File.Exists(@"C:\test.txt"))
{
File.Delete(@"C:\test.txt");
}
正如Chris在評論中指出的那樣,你實際上不需要執行File.Exists
檢查,因為如果文件不存在, File.Delete
不會引發異常,但是如果你使用絕對路徑,你需要檢查以確保整個文件路徑是有效的。 我如何刪除C#中的文件,例如C:\test.txt
,儘管像在批處理文件中應用相同類型的方法,例如
if exist "C:\test.txt"
delete "C:\test.txt"
else
return nothing (ignore)
如果您使用FileStream從該文件讀取然後想要將其刪除,請確保在調用File.Delete(路徑)之前關閉FileStream。 我有這個問題。
var filestream = new System.IO.FileStream(@"C:\Test\PutInv.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(@"C:\Test\PutInv.txt");
您可以使用以下命令導入System.IO
名稱空間:
using System.IO;
如果文件路徑代表文件的完整路徑,則可以檢查其存在並將其刪除,如下所示:
if(File.Exists(filepath))
{
File.Delete(filepath);
}
if (System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
{
// Use a try block to catch IOExceptions, to
// handle the case of the file already being
// opened by another process.
try
{
System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
if (System.IO.File.Exists(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
但
System.IO.File.Delete(@"C:\test.txt");
只要該文件夾存在就會執行相同操作。