How to delete a read-only file?

I have a garbage catalog in which I upload downloads, one-time projects, drafts and other various things that can be useful for several days, but they do not need to be saved forever. To prevent this directory from intercepting my computer, I wrote a program that will delete all files older than the specified number of days and register some statistics about the number of deleted files and their size just for fun.

I noticed that several project folders live much longer than necessary, so I began to research. In particular, it seemed that the folders for the projects in which I used SVN were sticking around. It turns out that the read-only files in the .svn directories are not deleted. I just did a simple test in a read-only file and found that System.IO.File.Delete and System.IO.FileInfo.Delete would not delete the read-only file.

I do not need to protect files in this particular directory; if something important in it is in the wrong place. Is there a .NET class that can delete read-only files, or will I have to check read-only attributes and erase them?

+66
c # file
Nov 05 '08 at 17:13
source share
5 answers

Adding sample code to Tim's answer:

 using System.IO; File.SetAttributes(filePath, FileAttributes.Normal); File.Delete(filePath); 
+133
Nov 05 '08 at 17:23
source share

According to the File.Delete documentation, you will have to disable the read-only attribute. You can set file attributes using File.SetAttributes () .

+46
Nov 05 '08 at 17:19
source share

Equivalent if you are working with a FileInfo object:

 file.IsReadOnly = false; file.Delete(); 
+16
Nov 29 '11 at 12:21
source share

Why do you need to check? Just force clear the read-only flag and delete the file.

+2
Nov 05 '08 at 17:15
source share

I think I would rather put

 >del /F * 

into a scheduled task. Maybe wrapped in a batch file to register statistics.

Did I miss something?

+2
Nov 05 '08 at 17:18
source share



All Articles