如何删除文件后,检查是否存在

我怎样才能删除C#文件,例如C:\test.txt ,尽pipe像batch file中应用相同的方法,例如

 if exist "C:\test.txt" delete "C:\test.txt" else return nothing (ignore) 

这是非常简单的使用File类。

 if(File.Exists(@"C:\test.txt")) { File.Delete(@"C:\test.txt"); } 

正如Chris在注释中指出的那样,实际上并不需要执行File.Exists检查,因为如果文件不存在, File.Delete不会引发exception,但是如果使用绝对path,则需要检查以确保整个文件path是有效的。

使用System.IO.File.Delete像这样:

System.IO.File.Delete(@"C:\test.txt")

从文档:

如果要删除的文件不存在,则不会抛出exception。

 if (System.IO.File.Exists(@"C:\test.txt")) System.IO.File.Delete(@"C:\test.txt")); 

 System.IO.File.Delete(@"C:\test.txt"); 

只要文件夹存在就会做同样的事情。

如果您想避免DirectoryNotFoundException ,则需要确保文件的目录确实存在。 File.Exists完成这一点。 另一种方法是使用PathDirectory实用程序类,如下所示:

 string file = @"C:\subfolder\test.txt"; if (Directory.Exists(Path.GetDirectoryName(file))) { File.Delete(file); } 
  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(File.Exists(path)) { File.Delete(path) } else { ;//donothing } 

您可以使用以下命令导入System.IO名称空间:

 using System.IO; 

如果文件path代表文件的完整path,则可以检查其存在并将其删除,如下所示:

 if(File.Exists(filepath)) { File.Delete(filepath)) } 

如果您正在使用FileStream从该文件读取然后想要删除它,请确保在调用File.Delete(path)之前closuresFileStream。 我有这个问题。

 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"); 

有时你想删除一个文件,无论是哪种情况(无论发生什么exception,请删除文件)。 对于这种情况。

 public static void DeleteFile(string path) { if (!File.Exists(path)) { return; } bool isDeleted = false; while (!isDeleted) { try { File.Delete(path); isDeleted = true; } catch (Exception e) { } Thread.Sleep(50); } } 

注意:如果指定的文件不存在,则不会引发exception。