【发布时间】:2011-09-17 12:22:14
【问题描述】:
如何在 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)
【问题讨论】:
【讨论】:
@?对我来说,它没有。
【讨论】:
An exception is thrown if the specified file does not exist。
System.IO.File.Delete(@"C:\test.txt"); 就足够了。谢谢
您可以使用以下方法导入 System.IO 命名空间:
using System.IO;
如果filepath代表文件的完整路径,可以检查其是否存在并删除,如下:
if(File.Exists(filepath))
{
try
{
File.Delete(filepath);
}
catch(Exception ex)
{
//Do something
}
}
【讨论】:
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 实现了这一点。另一种方法是使用Path 和Directory 实用程序类,如下所示:
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);
}
【讨论】:
如果您正在使用 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");
【讨论】:
using 语句,其中File.Delete() 将超出括号。在您的示例中,您还应该执行filestream.Dispose();。
有时你想删除一个文件(无论发生什么异常,请务必删除该文件)。对于这种情况。
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);
}
}
注意:如果指定的文件不存在,不会抛出异常。
【讨论】:
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(filePath))
{
System.IO.File.Delete(filePath);
System.Threading.Thread.Sleep(20);
}
Thread.sleep 将有助于完美工作,否则如果我们复制或写入文件将影响下一步。
我做的另一种方法是,
if (System.IO.File.Exists(filePath))
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(filePath);
}
【讨论】: