Hidden Attribute causes UnauthorizedAccessException in File.Copy

unauthorized-access-exception

If you are getting “System.UnauthorizedAccessException: Access to the path ‘destFileName’ is denied” when you call File.Copy to copy and overwrite a file, the two more obvious possible causes are documented on MSDN:

Exception Condition
UnauthorizedAccessException

The caller does not have the required permission.

-or-

destFileName is read-only.

I ran into a third possible cause last week. If the destination file has the hidden file attribute, it will also cause the UnauthorizedAccessException. I wrote a short code snippet to quickly verify it.

private static void Main(string[] args) {
    string fromFile = string.Format("from-{0:hhmmss}.txt", DateTime.Now);
    string toFile = string.Format("to-{0:hhmmss}.txt", DateTime.Now);
    File.Create(fromFile).Close();
    File.Create(toFile).Close();

    // try copy without hidden attribute
    try {
        Console.WriteLine("Try copy without hidden attribute>>>");
        File.Copy(fromFile, toFile, true);
        Console.WriteLine("File successfully copied");
    }
    catch (UnauthorizedAccessException ex) {
        Console.WriteLine("File not copied. System.UnauthorizedAccessException. {0}", ex.Message);
    }

    // add hidden attribute to dest file
    File.SetAttributes(toFile, File.GetAttributes(toFile) | FileAttributes.Hidden);

    // try copy with hidden attribute
    try {
        Console.WriteLine("\nTry copy with hidden attribute>>>");
        File.Copy(fromFile, toFile, true);
        Console.WriteLine("File successfully copied.");
    }
    catch (UnauthorizedAccessException ex) {
        Console.WriteLine("File not copied. System.UnauthorizedAccessException. {0}", ex.Message);
    }
}
/*
Outout:
Try copy without hidden attribute>>>
File successfully copied

Try copy with hidden attribute>>>
File not copied. System.UnauthorizedAccessException. Access to the path 'to-101146.txt' is denied.
*/