【问题标题】:how can i know file is already open or in use? [duplicate]我怎么知道文件已经打开或正在使用? [复制]
【发布时间】:2012-02-14 13:12:37
【问题描述】:

可能重复:
Is there a way to check if a file is in use?
Check if a file is open

我怎么知道文件已经打开或正在使用。

public bool FileIsLocked(string strFullFileName)
        {
            bool blnReturn = false;
            System.IO.FileStream fs;
            try
            {
                fs = System.IO.File.Open(strFullFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
                fs.Close();
            }
            catch (System.IO.IOException ex)
            {
                blnReturn = true;
            }
            return blnReturn;
        }

我发现上面的代码不能正常工作

【问题讨论】:

标签: c# .net file


【解决方案1】:

取自这里:Is there a way to check if a file is in use?

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】:

    尝试按照http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx 捕获UnauthorizedAccessException

    UnauthorizedAccessException 不继承自 IOException http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception.aspx

    【讨论】:

      【解决方案3】:

      我已经在这里回答了:Check if a file is open

      编辑

      FileInfo file = new FileInfo(path);
      

      功能

      protected virtual bool IsFileinUse(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();
           }
           return false; 
      }
      

      【讨论】:

      • @bkac - 检查更新的答案........
      • @bkac - 但为我工作,检查文件路径是否相同,数据是否存在......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2012-12-10
      相关资源
      最近更新 更多