在操作一个文件前想要获取当前文件的状态,避免正在打开的文件又再次的打开,代码参考网络以前已经写好,分享于己作为记录,也可作为他人的参考。

 

    #region Get file status
    [DllImport("kernel32.dll")]
    private static extern IntPtr _lopen(string lpPathName,int iReadWrite);
    
    [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(IntPtr hObject);
    
    private const int OF_READWRITE=2;
    private const int OF_SHARE_DENY_NONE=0x40;
    private static readonly IntPtr HFILE_ERROR=new IntPtr(-1);
    
    private static int getFileStatus(string fileFullName)
    {
      if(!File.Exists(fileFullName))
      {
        return -1;//file not exists
      }
      IntPtr handle=_lopen(fileFullName,OF_READWRITE|OF_SHARE_DENY_NONE);
      if(handle==HFILE_ERROR)
      {
        return 1;//aready open
      }
      CloseHandle(handle);
      return 0;//not open
    }
    #endregion

 

需要引用命名空间:

using System.Runtime.InteropServices;