Master_T
Master_T

Reputation: 7987

FileInfo.CopyTo() throws exception when trying to overwrite file

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:

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?

Upvotes: 0

Views: 1430

Answers (1)

Master_T
Master_T

Reputation: 7987

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);

Upvotes: 0

Related Questions