Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a read-only file?

Tags:

c#

.net

file

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?

like image 736
OwenP Avatar asked Nov 05 '08 17:11

OwenP


People also ask

Can not remove read only file system?

If the file belongs to you, you can either change the file's permissions or use the sudo command to delete the file as root. But if you're trying to delete a file that has write permissions and still can't delete it (or you see a "Read Only File System" error), you may need to remount the drive with proper permissions.

Why is my file read only?

Are the file properties set to read-only? You can check the file properties by right-clicking on the file and choosing Properties. If the Read-only attribute is checked, you can uncheck it and click OK.


2 Answers

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);
like image 183
Gulzar Nazim Avatar answered Oct 09 '22 19:10

Gulzar Nazim


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

like image 43
Tim Stewart Avatar answered Oct 09 '22 19:10

Tim Stewart