複製前確保檔案完成
在使用FileSystemWatcher 偵測目錄中檔案的建立並隨後複製它們的場景中到不同的位置,當涉及大檔案(> 10MB)時就會出現問題。由於複製過程在文件建立完成之前開始,可能會遇到「無法複製文件,因為它已被另一個程序使用」的錯誤。
解決方法:
唯一已知的解決方法是在啟動複製操作之前檢查檔案是否已鎖定。這可以透過一個函數來實現,該函數反覆檢查檔案是否正在使用,直到返回 false,表示該檔案不再被鎖定。
方法 1(直接複製):
private bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { // File still being written, processed, or doesn't exist return true; } finally { if (stream != null) stream.Close(); } // File not locked return false; }
方法二:
const int ERROR_SHARING_VIOLATION = 32; const int ERROR_LOCK_VIOLATION = 33; private bool IsFileLocked(string file) { // Check destination file status if (File.Exists(file)) { FileStream stream = null; try { stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (Exception ex2) { int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1); if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION)) { return true; } } finally { if (stream != null) stream.Close(); } } return false; }
以上是如何在複製前確保文件完成以防止'文件正在使用”錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!