首頁 >後端開發 >C++ >如何在複製前確保文件完成以防止'文件正在使用”錯誤?

如何在複製前確保文件完成以防止'文件正在使用”錯誤?

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-01-04 16:41:39425瀏覽

How to Ensure File Completion Before Copying to Prevent

複製前確保檔案完成

在使用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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn