c#检测文件是否可以删除

时间:2016-03-03 11:28:17

标签: c# file delete-file

我正在尝试完成检测文件是否能够删除的简单任务,例如:如果其他程序正在使用.dll您无法删除.dll - 这是我想要检测到的。好吧,希望这是有道理的。

到目前为止,我已经尝试了以下但没有运气:

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

1 个答案:

答案 0 :(得分:-1)

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?