Reputation: 1
I am doing an project from my school and I am trying to delete a file from Windows XP.
However, I encounter this error, even after I set the attribute of the file.
Access to the path is denied"
The file is in C:\Document and Settings\%user%\Local Settings\Temp
.
How can this be solved?
if(File.Exists(filePath))
{
FileSecurity sec = File.GetAccessControl(filePath);
sec.AddAccessRule(new FileSystemAccessRule(Environment.UserName,
FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(filePath, sec);
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
Upvotes: 0
Views: 3409
Reputation: 4469
So far, the code block is okay.
However, keep in mind the below things:
a. In case of Windows XP, with the user you logged in - make sure that the user is in administrator group and the user will have admin access, so any application running by the user will have admin privileges.
b. In case of other updated Windows like Vista, Windows 7, try running the application as an administrator ( right click on application and the click on "run as administrator" from the pop-up, while checking in development time - run your IDE as administrator ).
Hope this would be helpful.
Upvotes: 0
Reputation: 23
Check whether you have "admin" or related permission to delete the files.
If you have admin authority, then check whether the file which you have mentioned has other "rights" Ex: few MS files cannot be deleted.
Check whether you have specified the right file name.
If you have verified all these then this file either you have opened it or in your code you have not closed it to delete it.
Even if the above solution doesn't work then this file is either corrupted or some other user or yourself are still using this file which is not closed.
Upvotes: 0
Reputation: 15130
FileSecurity sets permissions on the file itself. Thats all great but it doesn't mean you have the permission to Delete it. Try running your app as an administrator and see if that makes a difference.
Upvotes: 2
Reputation: 887275
That means that another program is using the file.
You must close the file (or the entire program) before you can delete it.
If your program uses the file, make sure to close (not cross) the streams.
Upvotes: 0