Reputation: 159
I have following problem, I want to delete a file/directory, but the problem is following: I'm setting the FileAttribute.ReadOnly
to false with this code
var di = new DirectoryInfo("FileToDelete");
di.Attributes &= ~FileAttributes.ReadOnly;
Then I'm doing this
File.Delete("FileToDelete")
Then it throws this Exception:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: The access to the path "FileToDelete" has been denied. //Changed the Path to FileToDelete
Upvotes: 0
Views: 935
Reputation: 4733
What you are doing is you have an expression
di.Attributes &= ~FileAttributes.ReadOnly;
that is not assigned, used etc. nowhere in the code.
Also you are mixing DirectoryInfo and FileAttributes. This is just wrong. What you really want (from the description) is to set file not to be read only and then delete it.
So, you have to it like this
File.SetAttributes("FileToDelete", File.GetAttributes("FileToDelete") & ~FileAttributes.ReadOnly);
File.Delete("FileToDelete");
also please note that the exception you're getting can still occur if you will not have sufficient permissions https://msdn.microsoft.com/en-us/library/system.io.file.setattributes%28v=vs.110%29.aspx
as for the directories
new DirectoryInfo("DirectoryToDelete").Attributes &= ~FileAttributes.ReadOnly;
Upvotes: 1
Reputation: 678
You have to 'apply' the attributes by using:
File.SetAttributes(path, attributes);
Upvotes: 0