c#检查文件是否打开

时间:2013-04-01 18:14:59

标签: c# file

我需要验证特定文件是否已打开以阻止该文件的副本。

我尝试了很多例子,但任何都行不通!我试试,例如,这个:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

我需要定位......我在哪里失败?建议?

2 个答案:

答案 0 :(得分:2)

如果您想知道您的应用是否已打开该文件,您只需将FileStream保存在字段中,然后将字段重置为null关闭流。然后,您只需测试并获取文件的FileStream

如果您想知道另一个应用程序是否已打开该文件,那么您无能为力。当您尝试打开文件时,您可能会收到异常。但即使您知道,那么您也无法阻止该文件的副本,因为您在应用程序中没有对该文件或其FileStream的引用。

答案 1 :(得分:2)

您可能会遇到线程争用情况,其中有文档示例将此用作安全漏洞。如果您检查该文件是否可用,但是然后尝试使用它,那么您可以抛出这一点,恶意用户可以使用该文件强制并利用您的代码。

你最好的选择是试试catch / finally试图获取文件句柄。

try
{
   using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))
   {
        // File/Stream manipulating code here
   }
} catch {
  //check here why it failed and ask user to retry if the file is in use.
}

看到另一个选项

https://stackoverflow.com/a/11060322/2218635

相关问题