1

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

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • The read-only doesn't prevent you from copying a file, but it *will* prevent you from moving it. Either the destination is read-only or you don't have read permission for the source file. – Panagiotis Kanavos Oct 24 '14 at 10:15

2 Answers2

9

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:

  1. You copied the file from source to destination. The destination path did not exist originally. The file was copied successfully.
  2. The original source file had the read only attribute set. And so that attribute was transferred to the destination file.
  3. You subsequently attempt to copy to the same destination path, but since a file with that path exists, and has the read only attribute, the action fails.
Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Correct. I didn't see the file because when copying, the original timestamp was retained so I didn't see it appear (the file-names are all pretty similar) - and then the file _modification_ failed so it wasn't changing the timestamp. Thanks! – Mr. Boy Oct 24 '14 at 10:16
4

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.

Peter
  • 27,590
  • 8
  • 64
  • 84