如何在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)
当前回答
这是最简单的方法,
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);
}
其他回答
使用File类,这非常简单。
if(File.Exists(@"C:\test.txt"))
{
File.Delete(@"C:\test.txt");
}
正如Chris在评论中指出的,实际上不需要执行File。自文件以来存在检查。如果文件不存在,Delete不会抛出异常,但如果使用绝对路径,则需要检查以确保整个文件路径有效。
if (File.Exists(path))
{
File.Delete(path);
}
if (System.IO.File.Exists(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
but
System.IO.File.Delete(@"C:\test.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);
}
您可以导入系统。IO命名空间使用:
using System.IO;
如果filepath是文件的全路径,可以检查是否存在并删除。
if(File.Exists(filepath))
{
try
{
File.Delete(filepath);
}
catch(Exception ex)
{
//Do something
}
}