1. 程式人生 > 實用技巧 >C# WinForm 檢測檔案是否被佔用

C# WinForm 檢測檔案是否被佔用

#region 檢測檔案狀態及操作方式選擇
[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); /// <summary> /// 檢測檔案是否只讀或被使用 /// </summary> /// <param name="FileNames">要檢測的檔案</param> /// <returns>true可用,false在用或只讀</returns> public static bool CheckFilesState(string fileName) { if (!File.Exists(fileName)) return true;//檔案不存在 if
((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) return false; //檔案只讀 IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR) return false; //檔案被佔用 CloseHandle(vHandle); //檔案沒被佔用 return
true; } /// <summary> /// 檢測檔案是否只讀或被使用,並由使用者選擇是否繼續操作 /// </summary> /// <param name="fileFullName">要檢測的檔案</param> /// <returns>true已在用,false未用</returns> public static bool FileHasOpened(string fileFullName) { bool lOpened = false; bool lRetry = true; do { if (!CheckFilesState(fileFullName)) { if (DialogResult.Cancel == MessageBox.Show("檔案只讀或已經被開啟,請處理後再操作!", "系統錯誤!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning)) { lRetry = false; lOpened = true; } } else lRetry = false; } while (lRetry); return lOpened; } #endregion