Cannot system.io.file.delete after system.io.file.copy() - permission error

ptu

Member
Joined
Oct 24, 2003
Messages
5
Heres my code

System.IO.File.Copy("C:\Program Files\My Program\Temp\temp.txt", "C:\temp2.txt")
System.IO.File.Delete("C:\Program Files\My Program\Temp\temp2.txt")

I get an exception System.UnauthorizedAccessException "Access to the patch "C:\Program Files\My Program\Temp\temp2.txt" is denied."

Are there other classes or methods I could use to workaround this.
 
Was that file open in some other program (or perhaps by a StreamWriter/Reader in your own program), and are you sure the file exists?
 
Two things I should have mentioned...

1. This code is in a web application
2. When I manually view the security properties of temp.txt "everyone" has full control. However, when I try to view the security properties of temp2.txt I get the following dialog box "You do not have permission to view or edit the current permission settings for temp2.txt, but you can take ownership or change auditing settings."

VolteFace, I am sure no other program is using "temp2.txt" and this is the only place in my code that references "temp2.txt".
 
You need to make sure the ASP.NET user account that the app is using has appropriate permissions.
 
After adding ASPNET to the administrators group I am able to delete the copied file. However, this is not going to be a valid option because this could create a security hole, "big enough for me to drive my hummer thru".

Does anyone know of a way for the file that is copied to simply inherit the original files permissions?
 
Normally when you copy a file from an NTFS partition to the same NTFS partition the permissions are duplicated. However, your code is not trying to delete the same file that it is copying. Maybe this is intended or just a typo, but the two lines of code seem to be unrelated.

System.IO.File.Copy("C:\Program Files\My Program\Temp\temp.txt", "C:\temp2.txt")

^This code creates "C:\temp2.txt" which should have the same permissions as the original file.

System.IO.File.Delete("C:\Program Files\My Program\Temp\temp2.txt")

^This code tries to delete a different file than the one mentioned above. Therefore "C:\Program Files\My Program\Temp\temp2.txt" may not have the same permissions as the original file you did the copy on.

Make sense?
 
You could also give the ASP.NET user delete access to the directory where the file is being written in case the copied file is getting its permissions from the directory above it (so they would have read, write, and delete access to files in that directory).

Just dont give execute access and write access to the same files.
 
Everyone has full control of the folder directory and the original file. I dont know why neither one of those permissions are inherited...
 
Back
Top