检查文件是否已打开 [英] Check if a file is open

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

问题描述

有没有办法找到文件是否已经打开与否?


解决方案

 受保护的虚拟BOOL IsFileinUse(FileInfo的文件)
{
     的FileStream流= NULL;     尝试
     {
         流= file.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.None);
     }
     赶上(IOException异常)
     {
         //文件不可用,因为它是:
         //仍然被写入
         //或者被另一个线程正在处理
         //或不存在(已处理)
         返回true;
     }
     最后
     {
         如果(流!= NULL)
         stream.Close();
     }
     返回false;
}

Is there a way to find if a file is already open or not?

解决方案

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

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

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