如何在c#中删除一个文件,例如C:\test.txt,尽管应用类似于批处理文件中的相同方法。
if exist "C:\test.txt"
delete "C:\test.txt"
else
return nothing (ignore)
如何在c#中删除一个文件,例如C:\test.txt,尽管应用类似于批处理文件中的相同方法。
if exist "C:\test.txt"
delete "C:\test.txt"
else
return nothing (ignore)
当前回答
如果您希望避免DirectoryNotFoundException异常,则需要确保文件的目录确实存在。文件。存在实现了这一点。另一种方法是像这样利用Path和Directory实用程序类:
string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}
其他回答
如果您正在使用FileStream读取该文件,然后想要删除它,请确保在调用file . delete (path)之前关闭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");
这是最简单的方法,
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
System.Threading.Thread.Sleep(20);
}
线程。睡眠将有助于完美的工作,否则,它将影响下一步如果我们做拷贝或写入文件。
另一种方法是,
if (System.IO.File.Exists(filePath))
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(filePath);
}
如果您希望避免DirectoryNotFoundException异常,则需要确保文件的目录确实存在。文件。存在实现了这一点。另一种方法是像这样利用Path和Directory实用程序类:
string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}
像这样使用System.IO.File.Delete:
System.IO.File.Delete(@“C: \用法”)
从文档中可以看到:
如果要删除的文件不存在,则不会抛出异常。
if (System.IO.File.Exists(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
but
System.IO.File.Delete(@"C:\test.txt");
只要文件夹存在,就会这样做。