如何知道文件是否已经被打开或正在使用?

3

可能是重复问题:
有没有一种方法可以检查文件是否正在使用?
检查文件是否已打开

我如何知道文件是否已经打开或正在使用。

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

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

https://dev59.com/EnVD5IYBdhLWcg3wXaid - vulkanino
1
请注意,使用此类函数获取的信息可能在您使用它的那一刻就已经过时了。文件可能会被锁定,即使您检查过它没有被锁定,反之亦然。通常最好尝试您需要执行的操作,并在发生错误时做出反应。 - Christian.K
我得到了这段代码,但它没有正常工作。 - bhaveshkac
重复的副本?https://dev59.com/KU7Sa4cB1Zd3GeqP6s-l - kenny
3个回答

0

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

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

0

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

编辑

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 - 不过对我来说是有效的,请检查文件路径是否相同并确认数据是否存在。 - Pranay Rana

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接