繁体   English   中英

c#检查文件是否打开

[英]c# check if file is open

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

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

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

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

如果您想知道应用程序是否已打开文件,则只需将FileStream保存在字段中,并在关闭流时将该字段重置为null 然后你可以简单地测试并获取文件的FileStream

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

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

你最好的选择是尝试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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM