C# 如何判断指定文件是否正被其它程序使用

C# 如何判断指定文件是否正被其它程序使用

 

起因:项目中发现在操作文件时,系统经常抛出异常,表示文件正被其它程序占用。

需求:为了事先判断,以确认指定的文件是否正被其它程序使用,需要方法进行判断。

实现:

       /// <summary>
       /// 返回指示文件是否已被其它程序使用的布尔值
       /// </summary>
       /// <param name="fileFullName">文件的完全限定名,例如:“C:\MyFile.txt”。</param>
       /// <returns>如果文件已被其它程序使用,则为 true;否则为 false。</returns>
       public static Boolean FileIsUsed(String fileFullName)
       {
           Boolean result = false;

           //判断文件是否存在,如果不存在,直接返回 false
           if (!System.IO.File.Exists(fileFullName))
           {
               result = false;

           }//end: 如果文件不存在的处理逻辑
           else
           {//如果文件存在,则继续判断文件是否已被其它程序使用

               //逻辑:尝试执行打开文件的操作,如果文件已经被其它程序使用,则打开失败,抛出异常,根据此类异常可以判断文件是否已被其它程序使用。
               System.IO.FileStream fileStream = null;
               try
               {
                   fileStream = System.IO.File.Open(fileFullName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite,System.IO.FileShare.None);

                   result = false;
               }
               catch (System.IO.IOException ioEx)
               {
                   result = true;
               }
               catch (System.Exception ex)
               {
                   result = true;
               }
               finally
               {
                   if (fileStream != null)
                   {
                       fileStream.Close();
                   }
               }

           }//end: 如果文件存在的处理逻辑

           //返回指示文件是否已被其它程序使用的值
           return result;

       }//end method FileIsUsed

原文地址:https://www.cnblogs.com/changbaishan/p/3103644.html