C#系列

判断文件是否被占用
public class FileStatus    {      
[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);    
public static int FileIsOpen(string fileFullName)     
{          
if (!File.Exists(fileFullName))        
{              
return -1;// 不存在文件       
}           
  IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);    
  if (handle == HFILE_ERROR)       
  {            
    return 1;// 表示被占用     
  }           
  CloseHandle(handle);     
  return 0;      
}   
}  

 


版本号 #1
由 叶子 创建于 21 三月 2025 10:20:17
由 叶子 更新于 21 三月 2025 10:21:57