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

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

read only

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

System.Authorizedaccessexception was unhandled

If it is a file whose "read-only" attribute is unchecked, the deletion process is performed without problems.

How do I remove files marked with this attribute?

 5
Author: Comunidade, 2014-01-03

3 answers

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();
 10
Author: talles, 2014-01-03 18:38:14

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 which is enum with flags (read more). With this you can remove the ReadOnly attribute and your file can be deleted.

new FileInfo("test.txt").Attributes &= ~FileAttributes.ReadOnly;
 0
Author: BrunoLM, 2017-04-12 07:33:53

Add this assembly:

using System.IO;

Add this line after the directory is declared:

File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
//path = Diretório

.Hidden = property.

Example:

  • .Normal, for normal.
  • .ReadOnly , for Read-Only.
  • .Archive for backup, etc...

More info: http://msdn.microsoft.com/en-us/library/system.io.file.setattributes (v=vs. 110).aspx

 0
Author: Cosmo José, 2015-01-18 17:00:11