如何使用 c# 更改文件夹中每个文件的只读文件属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/191399/
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 change the Read-only file attribute for each file in a folder using c#?
提问by
How do I change the Read-only file attribute for each file in a folder using c#?
如何使用 c# 更改文件夹中每个文件的只读文件属性?
Thanks
谢谢
回答by Jeffrey L Whitledge
foreach (string fileName in System.IO.Directory.GetFiles(path))
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
// or
fileInfo.IsReadOnly = true;
}
回答by Tom Ritter
Use File.SetAttributesin a loop iterating over Directory.GetFiles
在遍历Directory.GetFiles的循环中使用File.SetAttributes
回答by mathieu
You can try this : iterate on each file and subdirectory :
你可以试试这个:迭代每个文件和子目录:
public void Recurse(DirectoryInfo directory)
{
foreach (FileInfo fi in directory.GetFiles())
{
fi.IsReadOnly = false; // or true
}
foreach (DirectoryInfo subdir in directory.GetDirectories())
{
Recurse(subdir);
}
}
回答by Mike
If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:
如果您想使用模式匹配删除只读属性(例如文件夹中带有 .txt 扩展名的所有文件),您可以尝试以下操作:
Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);