C#如何判断文件处于打开状态

来源:互联网 发布:象棋ai算法 编辑:程序博客网 时间:2024/05/14 13:55

对于应用程序,有时候可能需要判断某个文件是否已经被打开,也就是指是否被某个流连接着。这在对文件的读写比较频繁的程序中尤为重要,因为一个文件同一时刻只能有一个流连接的。下面的代码也许能有所帮助。

[csharp] view plaincopyprint?
  1. public class FileStatus  
  2.    {  
  3.        [DllImport("kernel32.dll")]  
  4.        private static extern IntPtr _lopen(string lpPathName, int iReadWrite);  
  5.   
  6.        [DllImport("kernel32.dll")]  
  7.        private static extern bool CloseHandle(IntPtr hObject);  
  8.   
  9.        private const int OF_READWRITE = 2;  
  10.   
  11.        private const int OF_SHARE_DENY_NONE = 0x40;  
  12.   
  13.        private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);  
  14.   
  15.        public static int FileIsOpen(string fileFullName)  
  16.        {  
  17.            if (!File.Exists(fileFullName))  
  18.            {  
  19.                return -1;  
  20.            }  
  21.   
  22.            IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);  
  23.   
  24.            if (handle == HFILE_ERROR)  
  25.            {  
  26.                return 1;  
  27.            }  
  28.   
  29.            CloseHandle(handle);  
  30.   
  31.            return 0;  
  32.        }  
  33.    }  

测试:

[csharp] view plaincopyprint?
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         string testFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"testOpen.txt";  
  6.   
  7.         FileStream fs = new FileStream(testFilePath, FileMode.OpenOrCreate, FileAccess.Read);  
  8.   
  9.         BinaryReader br = new BinaryReader(fs);  
  10.   
  11.         br.Read();  
  12.   
  13.         Console.WriteLine("文件被打开");  
  14.   
  15.         int result =FileStatus.FileIsOpen(testFilePath);  
  16.   
  17.         Console.WriteLine(result);  
  18.   
  19.         br.Close();  
  20.   

    结果:

    代码下载:http://download.csdn.net/detail/yysyangyangyangshan/4914142