c#检测一个文件是否能被删除
问题描述:
我想完成检测文件是否能被删除的简单任务,例如:如果一个.dll
被另一个程序使用,你不能删除.dll
- 这是我想要能够检测到的。那么希望是有道理的。c#检测一个文件是否能被删除
到目前为止,我已经试过,没有运气以下:
try
{
System.IO.File.Delete(@"C:\Program Files\MyTestFiles\testing.dll");
}
catch
{
Console.WriteLine("Unable to delete file");
}
,我已经试过:
System.IO.File.Delete(@"C:\Program Files\MyTestFiles\testing.dll");
if(File.Exists(@"C:\Program Files\MyTestFiles\testing.dll"))
{
Console.WriteLine("Error: Unable to delete file");
}
else
{
Console.WriteLine("Successfully deleted file!");
}
答
private bool IsFileLocked()
{
try
{
using (File.Open(@"C:\Program Files\MyTestFiles\testing.dll", FileMode.Open))
{
return false;
}
}
catch (IOException e)
{
// file locked
return true;
}
}
或更好的解决方案,你可以使用:How do I find out which process has a file open?
+2
这只会导致[种族情况](https://en.wikipedia.org/wiki/Race_condition)。仅仅因为当前文件被解锁,并不意味着当发起删除请求时它将被解锁。 – Phylogenesis
+0
很好的答案,完美的作品:) – C0d1ng
什么意思,没有运气?它没有按预期工作吗?你有错误吗?如果删除失败,通常'File.Delete'应该会引发异常。 – HimBromBeere
这是不是按预期方式工作?我完全期望第一个例子要么删除文件,要么失败...... – David
如果存在这样的方法,那么当文件实际上被删除时不能保证它仍然保留。如果你不介意自己删除文件,那么你可以做的最好的就是尝试。如果失败,那么未来的尝试可能会失败,如果成功,问题就会解决。 – Neil