I have the following piece of code in a .NET 6 app that copies some files to a different destination on the file system:
DirectoryInfo targetDir = GetTargetDir();
foreach (FileInfo fi in GetFilesToCopy())
{
fi.CopyTo(Path.Combine(targetDir.FullName, fi.Name), true);
}
As you can see, I'm passing true
to the .CopyTo()
method, so it overwrites the file if it already exists.
However, this seems to not work properly:
- If the destination file does NOT exist, the copy works fine
- If the destination file DOES exist, however, the copy operation fails and throws a
UnauthorizedAccessException
with an error message like'Access to the path 'C:\my destination dir\my destination file.ext' is denied.'
I've checked the method documentation, and it says that that exception is thrown if the destination is a directory or if we're trying to copy to a different drive. However, I'm not doing any of those things (and anyway it doesn't explain why it works if the file does not exist)
I've checked all I could think of, and it all seems in order:
- The user running the application has permission to write to that location and is the owner of the existing files
- The files are not in use, I can easily delete them using windows explorer or cmd
- I've also tried running the code as administrator (even though it shouldn't be needed) but same error occurs
Can anyone tell me why this is happening?
Apparently the problem was the files have the Read Only attribute (thanks to @nilsK for pointing me in the right direction).
I've resolved this with the following code: