C# 如何删除只读文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/265896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I delete a read-only file?
提问by OwenP
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.
我注意到一些项目文件夹的寿命比它们应该的要长,所以我开始调查。特别是,我使用过 SVN 的项目的文件夹似乎一直存在。事实证明 .svn 目录中的只读文件没有被删除。我只是对只读文件做了一个简单的测试,发现System.IO.File.Delete
并System.IO.FileInfo.Delete
不会删除只读文件。
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?
我不在乎保护这个特定目录中的文件;如果有重要的东西在那里,它就在错误的地方。是否有可以删除只读文件的 .NET 类,或者我是否必须检查只读属性并删除它们?
采纳答案by 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().
根据File.Delete 的文档,您必须去除只读属性。您可以使用File.SetAttributes()设置文件的属性。
using System.IO;
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
回答by Adam Liss
Why do you need to check? Just forcibly clear the read-only flag and delete the file.
为什么需要检查?只需强行清除只读标志并删除文件即可。
回答by mkoeller
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?
我错过了什么吗?
回答by Tim Stewart
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().
根据File.Delete 的文档,您必须去除只读属性。您可以使用File.SetAttributes()设置文件的属性。
回答by Neil
The equivalent if you happen to be working with a FileInfo
object is:
如果您碰巧正在处理一个FileInfo
对象,则等效的是:
file.IsReadOnly = false;
file.Delete();