If you want to copy a file to a folder, which is polled by a import service, you want the import service to start processing the file, when it is fully copied to the folder. This can be done with the following code:

 

/// <summary>
/// Copy a file to a destinationfolder, with the fileextension renamed to [tempFileExtension]
/// After copy, rename the destination file to it's original file extension
/// This methode can be used in scenario's, where a service is polling a folder and you don't want the service to start processing the file, when it is not fully copied yet
/// </summary>
/// <param name="sourceFolder">Can't be empty</param>
/// <param name="destinationFolder">Can't be empty</param>
/// <param name="fileName">Can't be empty. Should be the name of the file, including the file extension</param>
/// <param name="tempFileExtension">Can't be empty</param>
public static void SaveFileCopy(string sourceFolder, string destinationFolder, string fileName, string tempFileExtension)
{
    // Determine source file path
    string sourceFile = Path.Combine(sourceFolder, fileName);

    // Determine temp destination file path
    string tempDestinationFile = string.Format("{0}{1}", Path.Combine(destinationFolder, fileName), tempFileExtension);

    // Set temp destination file to [not-readonly]
    if (File.Exists(tempDestinationFile))
    {
        File.SetAttributes(tempDestinationFile, FileAttributes.Normal);
    }

    // Copy the file as temp file extension
    File.Copy(sourceFile, tempDestinationFile, true);

    // Determine destination file path
    string destinationFile = Path.Combine(destinationFolder, fileName);

    // Set destination file to [not-readonly]
    if (File.Exists(destinationFile))
    {
        File.SetAttributes(destinationFile, FileAttributes.Normal);
    }

    // Delete the destination file if it exists
    if (File.Exists(destinationFile)) { File.Delete(destinationFile); }

    // Rename the file to it's original file extension
    File.Move(tempDestinationFile, destinationFile);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.