Reputation: 63806
System.IO.File.Copy
is failing when the source file has the read-only attribute set.
Copying to I get an error:
Access to the path
<destination>
is denied. (System.UnauthorizedAccessException)
I have a scenario where I am copying a template file to a destination path prior to modifying it, and for safety I'd rather the template was read-only.
Why can't I copy a read-only file in this way, and how can I achieve what I want most easily/sensibly? And... why is the exception about the destination file when this file is never created?
note: whether the copied file is read-only or not I don't care, that's easy to fix
Upvotes: 1
Views: 33233
Reputation: 27944
There is nothing in system.io.file.copy that prevents you from coping a readonly file, I guess your problem is in the destination. Because your file is readonly, the readonly attribute is copied. Next you try to override the destination with the readonly attribute which fails. Check if there is a file at the destination location before you copy the file.
Access to the path is denied. (System.UnauthorizedAccessException)
Means you do not have access to the destination folder. Are you coping to c:\? Make sure the user has the right privileges to write in you destination folder.
Upvotes: 4
Reputation: 613382
You have diagnosed this incorrectly. File copying will never fail because the source is read only. File copying will fail if the existing destination file is read only. The simple remedy is to clear the read only attribute on the destination file before copying. The answer from sll here explains how to do that: How to remove a single Attribute (e.g. ReadOnly) from a File?
Most likely what has happened is that:
Upvotes: 9