File.Copy method makes file inaccessible

Vale picture Vale · Jun 6, 2011 · Viewed 8k times · Source

I am struggling with this for some time now. I can not access a file after I call File.Copy method. Here is what I tried:

File.Copy(sourceFile, destinationFile, true);
FileStream fs = File.Open(destinationFile, FileMode.Open);

I am getting UnauthorizedAccessException on the second line. It says: Access to the path ... is denied. I have also tried suggestion stated here but that didn't work.

Any help is appreciated.

EDIT: Here is what I found out. If I do this:

File.Copy(sourceFile, destinationFile, true);
FileStream fs = File.Open(destinationFile, FileMode.Open, FileAccess.Read);

It doesn't throw exception. The file I am trying to access is read only. So, I tried to remove read only attribute like this:

File.Copy(sourceFile, destinationFile, true);
FileInfo fileInfo = new FileInfo(destinationFile);
fileInfo.IsReadOnly = false;
FileStream fs = File.Open(destinationFile, FileMode.Open, FileAccess.ReadWrite);

And I get the same exception as before. By the way, I checked if I can open file manually and edit it, and I can. Of course, when I uncheck read only check box. I have also checked file attributes in windows explorer while debugging, right after the third line, and the file is no longer read only. Having all that in checked, I don't understand why is the exception being thrown on the fourth line.

Answer

Kieren Johnstone picture Kieren Johnstone · Jun 6, 2011

Are you sure it's ONLY files copied using File.Copy that you can't open, and not every file in the target folder? And is this a regular NTFS folder, or network share?

If you are running an antivirus or security software, try disabling it. After a file is created they will often open a file to scan it.

Update

According to http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx - UnauthorizedAccessException thrown by File.Open will not give the message 'Access to the path... is denied'. (edit: I can't see that message for File.Copy either, so this might be wrong)

I suspect it is your File.Copy that fails with that exception, and you don't have rights to read the source file, or write the target file. You're probably looking at the highlighted source code line, which shows the next line to be exectued.

So - maybe your copy fails, not the File.Open ?