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

本文关键字:文件 我怎么知道 | 更新日期: 2023-09-27 18:24:38

可能的重复项:
有没有办法检查文件是否正在使用中?
检查文件是否已打开

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

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

我发现上面的代码无法正常工作

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

从这里取: 有没有办法检查文件是否正在使用中?

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

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

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

我之前已经在这里回答过:检查文件是否已打开

编辑

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