tags:

views:

4712

answers:

4

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?

+2  A: 

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

Adam Liss
+1  A: 

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?

mkoeller
Yes. He wants to delete A file when it is of particular age. Not all the files every period.
DrFloyd5
He doesn't want to delete all files, just all files older than a certain amount of time.
Tim Stewart
+13  A: 

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().

Tim Stewart
I accepted this one for being first.
OwenP
It's not about being first.
VVS
+36  A: 

Adding some sample code to Tim's answer:

using System.IO;

File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
Gulzar
You get an upvote for being right, but your answer came in after Tim Stewart's which said the same thing.
OwenP
thats fine. Tim deserves it. thought some code will help.
Gulzar