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:
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:
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:
string destFile = Path.Combine(targetDir.FullName, fi.Name);
if (File.Exists(destFile))
{
File.SetAttributes(destFile, FileAttributes.Normal);
}
fi.CopyTo(destFile, true);