-1

When I try to delete an write protected file, I get an UnauthorizedAccessException. Permissions are fine, I can delete the file, if I remove the write-protection-box in Explorer->File properties.

How can I delete the file anyway?

MHolzmayr
  • 1,541
  • 1
  • 12
  • 22

1 Answers1

3

As long as you have enough rights on that file (permissions), you can remove all attributes on that file and then delete it:

var fileName = "c:\\temp\\test.txt"
// Handle write protected files: Remove all special attributes.
File.SetAttributes(fileName, FileAttributes.Normal);
File.Delete(fileName);
MHolzmayr
  • 1,541
  • 1
  • 12
  • 22
  • Not sure why this is downvoted. Seems to be the right answer (and you are allowed to answer your own questions). Might be a duplicate tho. – Matthew Watson Sep 01 '16 at 12:54
  • I was looking for an answer (but apparently searched for the wrong term "write-protected") which gave no SO-matches. So I thought "ok, lets help someone who searches for this, too". Anyway, this way, even with downvote and duplicates, the next guy will find an answer more quickly ;-) – MHolzmayr Sep 02 '16 at 13:35