Home >Backend Development >C++ >How to Ensure a File Is Completely Written Before Copying It?

How to Ensure a File Is Completely Written Before Copying It?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 12:07:41424browse

How to Ensure a File Is Completely Written Before Copying It?

Wait Until File Is Completely Written

When a file is created in a watched directory, a common task is to copy it to a different location. However, large file transfers can lead to failures due to the file not being completely written before the copy process begins.

To address this issue, a workaround involves checking the file's status before copying. One method is to use the IsFileLocked function, which returns True if the file is still being written or processed by another thread. Here's an example:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    return false;
}

This code can be incorporated into your FileSystemWatcher_Created event handler:

public static void listener_Created(object sender, FileSystemEventArgs e)
{
    while (IsFileLocked(new FileInfo(e.FullPath)))
    {
        // Wait for file to finish writing
    }

    File.Copy(e.FullPath, @"D:\levan\FolderListenerTest\CopiedFilesFolder\" + e.Name);
}

Alternatively, you can use the following method:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    if (File.Exists(file) == true)
    {
        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;
}

The above is the detailed content of How to Ensure a File Is Completely Written Before Copying It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn