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:
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?
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();
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;
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