有没有办法检查文件是否正在使用/打开 [英] Is there a way to check if a file is in use/opened

查看:83
本文介绍了有没有办法检查文件是否正在使用/打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iam尝试检查文件是否正在使用c#

i想查看简单的文本文件



我尝试过:



iam try to check that the file is in use or not in c#
i want to check the simple text file

What I have tried:

public static bool IsFileLocked(string filePath) 
        {
            bool lockStatus = false;
            try
            {
                using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) 
                {
                    // File/Stream manipulating code here

                    lockStatus = !fileStream.CanWrite;
                    
                }
            }
            catch
            {
                //check here why it failed and ask user to retry if the file is in use.
                lockStatus = true;
            }
            return lockStatus;
        }

推荐答案

try
{
using(FileStream fs = File.OpenWrite(strFileName)
{
if(fs == null)
return;
}
}
catch(UnauthorizedAccessException e)
{
//Here you know that the file is open by another app
}









或者其他,试试这个!!!









or Else, Try this!!!


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


试试这个!



Try this!

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, 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;
}


这篇关于有没有办法检查文件是否正在使用/打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆