DEV Community

Cover image for C# Copy files done right
Karen Payne
Karen Payne

Posted on

C# Copy files done right

Introduction

When copying a file using File.Copy the source date and time attributes, which are not retained.

Teaches

Shows how to copy a folder using a wildcard pattern, followed by setting the date/time and setting file attributes. Also, do the same for a single file, excluding file copying.

The above operations are part of a class project, and an exception in both methods use Serilog to write runtime exceptions to a log file.

Both methods set date, time, and file attributes done within a try/catch which logs exceptions to a log file in the executable folder under a folder named Logs.

public static bool SetFileDateTime(string sourceFile, string destinationFile)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(sourceFile);
    ArgumentException.ThrowIfNullOrWhiteSpace(destinationFile);

    if (!File.Exists(sourceFile))
    {
        throw new FileNotFoundException("Source file does not exist.", sourceFile);
    }

    if (!File.Exists(destinationFile))
    {
        throw new FileNotFoundException("Destination file does not exist.", destinationFile);
    }

    var sourceInfo = new FileInfo(sourceFile);

    try
    {
        File.SetCreationTimeUtc(destinationFile, sourceInfo.CreationTimeUtc);
        File.SetLastWriteTimeUtc(destinationFile, sourceInfo.LastWriteTimeUtc);
        File.SetLastAccessTimeUtc(destinationFile, sourceInfo.LastAccessTimeUtc);

        File.SetAttributes(destinationFile, File.GetAttributes(sourceFile));

        return true;
    }
    catch (Exception e)
    {
        Log.Error(e, "An error occurred while setting file timestamps for {DestinationFile}", destinationFile);
        return false;
    }

}
Enter fullscreen mode Exit fullscreen mode

shows important code

Source code Demo code

Summary

Setting file attributes is the proper way to copy files, and catching any runtime exceptions in a log file.

Top comments (0)