How to delete a file marked with the "Read only" attribute?

Asked

Viewed 1,977 times

5

I am trying to delete a file that is marked with the attribute "Read only":

somente leitura

Whenever the file is marked with the said attribute, I get the following exception:

System.Unauthorizedaccessexception was unhandled

If it is a file whose "Read only" attribute is unchecked, the deletion process is performed smoothly.

How do I remove files marked with this attribute?

3 answers

10


System.IO.File

File.SetAttributes(caminhoDoArquivo, ~FileAttributes.ReadOnly);
File.Delete(caminhoDoArquivo);

System.IO.Fileinfo (via property)

fileInfo.IsReadOnly = false;
fileInfo.Delete();

System.IO.Fileinfo (via attribute)

fileInfo.Attributes &= ~FileAttributes.ReadOnly;
fileInfo.Delete();

0

To remove read-only you need to remove this attribute. For this you can use the class FileInfo.

var info = new FileInfo("teste.txt");

And access the property Attributes that is Enum with flags (read more). With this you can remove the attribute ReadOnly and your file can be deleted.

new FileInfo("test.txt").Attributes &= ~FileAttributes.ReadOnly;

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.