『QQ:1353814576』

C#判断文件是否被其他程序占用


c#使用win32接口 判断当前文件是否被其他程序占用着

public static class FileStatusHelper  
    {  
        [DllImport("kernel32.dll")]  
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);  
  
        [DllImport("kernel32.dll")]  
        public static extern bool CloseHandle(IntPtr hObject);  
  
        public const int OF_READWRITE = 2;  
        public const int OF_SHARE_DENY_NONE = 0x40;  
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);  
  
        
        public static bool IsFileOccupied(string filePath)  
        {  
            IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE);  
            CloseHandle(vHandle);  
            return vHandle == HFILE_ERROR ? true : false;  
        }  
    }