3

我需要验证是否打开了特定文件以防止复制该文件。

我尝试了很多例子,但任何一个都不起作用!例如,我尝试这样做:

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;
}

我需要方向......我在哪里失败了?建议?

4

2 回答 2

2

您可能会因此受到线程竞争条件的影响,有记录的示例将其用作安全漏洞。如果您检查该文件是否可用,然后尝试使用它,您可能会在此时抛出,恶意用户可以使用它来强制和利用您的代码。

您最好的选择是尝试获取文件句柄的 try 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

于 2013-04-01T18:25:46.137 回答
2

If you want to know whether your application already had the file open, you should just save the FileStream in a field, and reset the field to null when you close the stream. Then you can simply test and get the FileStream of the file.

If you want to know whether another application already has the file open, then there is not much you can do. You'll might get an exception when you try to open the file. But even if you knew, then you wouldn't be able to prevent the copy of that file, because you don't have a reference to the file or its FileStream in your application.

于 2013-04-01T18:19:43.963 回答