如何在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(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
but
System.IO.File.Delete(@"C:\test.txt");
只要文件夹存在,就会这样做。
其他回答
if (File.Exists(Path.Combine(rootFolder, authorsFile)))
{
// If file found, delete it
File.Delete(Path.Combine(rootFolder, authorsFile));
Console.WriteLine("File deleted.");
}
动态
string FilePath = Server.MapPath(@"~/folder/news/" + IdSelect)
if (System.IO.File.Exists(FilePath + "/" + name+ ".jpg"))
{
System.IO.File.Delete(FilePath + "/" + name+ ".jpg");
}
删除目录下的所有文件
string[] files = Directory.GetFiles(rootFolder);
foreach (string file in files)
{
File.Delete(file);
Console.WriteLine($"{file} is deleted.");
}
if (System.IO.File.Exists(@"C:\test.txt"))
System.IO.File.Delete(@"C:\test.txt"));
but
System.IO.File.Delete(@"C:\test.txt");
只要文件夹存在,就会这样做。
像这样使用System.IO.File.Delete:
System.IO.File.Delete(@“C: \用法”)
从文档中可以看到:
如果要删除的文件不存在,则不会抛出异常。
您可以导入系统。IO命名空间使用:
using System.IO;
如果filepath是文件的全路径,可以检查是否存在并删除。
if(File.Exists(filepath))
{
try
{
File.Delete(filepath);
}
catch(Exception ex)
{
//Do something
}
}
if (File.Exists(path))
{
File.Delete(path);
}