How do I delete a file marked with the "read only" attribute?

5

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

Wheneverthefileismarkedwiththisattribute,Igetthefollowingexception:

  

System.UnauthorizedAccessExceptionwasunhandled

Ifitisafilewhose"Read-only" attribute is unchecked, the deletion process is performed smoothly.

How do I remove files marked with this attribute?

    
asked by anonymous 03.01.2014 / 19:14

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();
    
03.01.2014 / 19:38
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 Attributes property that 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;
    
03.01.2014 / 19:14
0

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 , to normal.
  • .ReadOnly , for read-only.
  • .Archive for backup, etc ...

More info: link

    
16.01.2015 / 21:09