我是编程的新手,仅使用C#编写的标准控制台程序。
我目前正在实习,并且被要求为他们设计一个小工具。
公平地讲,这项任务超出了我的前进方向,与我以前使用C#所做的没有什么不同。
该工具基本上必须执行以下操作:
用户选择要搜索的文件夹。
程序检查文件夹中的所有文件以及所有子文件夹,如果尚未选中,则检查写保护。
程序在所有文件上设置只读属性(如果当前没有)。
如果这不是寻求帮助的地方,请忽略我的问题。
谢谢阅读。
这几乎是该线程的复制粘贴:
完整的代码应类似于:
public void SetAllFilesAsReadOnly(string rootPath)
{
//this will go over all files in the directory and sub directories
foreach (string file in Directory.EnumerateFiles(rootPath, "*.*", SearchOption.AllDirectories))
{
//Getting an object that holds some information about the current file
FileAttributes attr = File.GetAttributes(file);
// set the file as read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(file,attr);
}
}
按照您的评论,为了更好地理解,让我们将其分为几部分:
拥有文件路径后,创建文件属性对象:
var attr = File.GetAttributes(path);
对于以下内容,您可能需要阅读一些有关枚举标志的内容,并按位阅读
这是您设置为的方式Read only
:
// set read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
这就是您取消设置为的方式Read only
:
// unset read-only
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
为了获取所有文件,您可以使用:
foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(file);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句