0

I'm making an application that copies files from one location to another, in my application I use thread pool so a few copies could be done together. When I tried to copy a read only file I got "access denied" exception. In order to fix that I changed the file attributes to RW by using this command:

File.SetAttributes(fileName, File.getAttributes(fileName) & ~FileAttributes.ReadOnly);

The file attributes was changed successfully but the copy command:

File.Copy(fileName, destinationPath, true);

returned the same "access denied" exception.

When I run this applucation again on the same file, everything is run properly and the copy success because the file attributes was changed in the last running. My question is why the file wasn't copied in the first application running even I changed the attributes first and just then I tried to copy the file?

ShaqD
  • 63
  • 1
  • 10
  • Maybe the `access denied` error meant the file is in use by another program; in this case, you can try to open it with `FileStream("...", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);` and manually copy it – Rubens Farias Aug 16 '15 at 08:20
  • Also, maybe you're trying to overwrite a readonly file, like explained here: http://stackoverflow.com/questions/18554108/c-sharp-unauthorizedaccessexception-in-file-copy – Rubens Farias Aug 16 '15 at 08:22
  • Hmya, don't wake up your shrinked-wrapped malware if you want this to consistently succeed. You can rename the file first so it can't stop you from copying. Then delete the renamed file, it will eventually disappear when the scan is completed. – Hans Passant Aug 16 '15 at 08:49

1 Answers1

0

I think your destination path is in a system folder or a program folder, that's why it does not let you put files in it. In order to solve this problem, you need to run your executable as administrator

Matty2
  • 55
  • 6