如何检查文件夹的写保护?

JFB*_*FBN 4 .net c#

我是编程的新手,并且只使用用C#编写的标准控制台程序.

我目前正在实习,我被要求为他们设计一个小工具.

公平地说,这项任务远远超过我的前进,而且与我以前用C#所做的完全不同.

该工具基本上必须执行以下操作:

用户选择要搜索的文件夹.

程序检查文件夹和所有子文件夹中的所有文件,如果尚未选中则检查写保护.

如果当前没有,程序会在所有文件上设置只读属性.

如果这不是寻求帮助的地方,请忽略我的问题.

谢谢阅读.

Avi*_*ner 8

这几乎是来自这个线程的复制粘贴:

完整的代码应该类似于:

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

在你的评论之后,为了更好地理解,让我们把它分解成碎片:

获得文件路径后,创建文件属性对象:

var attr = File.GetAttributes(path);
Run Code Online (Sandbox Code Playgroud)

对于以下内容,您可能希望阅读有关枚举标志和按位的内容

这是你如何设置为Read only:

// set read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
Run Code Online (Sandbox Code Playgroud)

这是你取消设置的方式Read only:

// unset read-only
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
Run Code Online (Sandbox Code Playgroud)

并获取您可以使用的所有文件:

 foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(file);
    }
Run Code Online (Sandbox Code Playgroud)