How do I delete a read-only file?

C#.NetFile

C# Problem Overview


I've got a junk directory where I toss downloads, one-off projects, email drafts, and other various things that might be useful for a few days but don't need to be saved forever. To stop this directory from taking over my machine, I wrote a program that will delete all files older than a specified number of days and logs some statistics about the number of files deleted and their size just for fun.

I noticed that a few project folders were living way longer than they should, so I started to investigate. In particular, it seemed that folders for projects in which I had used SVN were sticking around. It turns out that the read-only files in the .svn directories are not being deleted. I just did a simple test on a read-only file and discovered that System.IO.File.Delete and System.IO.FileInfo.Delete will not delete a read-only file.

I don't care about protecting files in this particular directory; if something important is in there it's in the wrong place. Is there a .NET class that can delete read-only files, or am I going to have to check for read-only attributes and strip them?

C# Solutions


Solution 1 - C#

According to File.Delete's documentation,, you'll have to strip the read-only attribute. You can set the file's attributes using File.SetAttributes().

using System.IO;

File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);

Solution 2 - C#

According to File.Delete's documentation,, you'll have to strip the read-only attribute. You can set the file's attributes using File.SetAttributes().

Solution 3 - C#

The equivalent if you happen to be working with a FileInfo object is:

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

Solution 4 - C#

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

Solution 5 - C#

Hm, I think I'd rather put

>del /F *

into a sheduled task. Maybe wrapped by a batch file for logging statistics.

Am I missing something?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOwenPView Question on Stackoverflow
Solution 1 - C#Gulzar NazimView Answer on Stackoverflow
Solution 2 - C#Tim StewartView Answer on Stackoverflow
Solution 3 - C#NeilView Answer on Stackoverflow
Solution 4 - C#Adam LissView Answer on Stackoverflow
Solution 5 - C#mkoellerView Answer on Stackoverflow