如何检查文件夹是否被设置为只读?

5
我是一名编程新手,只使用C#编写标准控制台程序。我目前正在实习,他们要求我为他们设计一个小工具。说实话,这个任务远远超出了我的能力范围,也与我之前使用C#制作的内容完全不同。该工具基本上需要执行以下操作:
用户选择要搜索的文件夹。 程序检查文件夹中的所有文件和所有子文件夹,并检查写入保护是否已经检查过。 如果尚未检查,程序将对所有文件设置只读属性。
如果这不是寻求帮助的地方,请忽略我的问题。感谢您的阅读。

感谢所有的回答。 恐怕这个任务对于我来说太大了。我只创建过非常简单的控制台应用程序,以前从未见过像“var”、“attr”这样的命令。当我们使用C#时,“Public void ______”等内容已经设置好,因此当你写这些时,我理解这对我来说太复杂了。我尝试将Avi Turner编写的最终代码复制/粘贴到我的程序中,但它无法识别“var”等命令。也许我把它写错了地方,我不知道。 - JFBN
@JFBN 我认为你没有理由自我打击。例如,var只是一个快捷方式,可以用对象类型(例如字符串)替换。我建议你不要轻易放弃,花时间学习。一开始总是比较难的。如果你需要在这个第一个任务上获得帮助,欢迎通过电子邮件联系我:avi.turner111@gmail.com - Avi Turner
@AviTurner 我刚刚意识到我实际上正在使用VB而不是C#.....太蠢了。通常当我创建一个新项目时,它会设置为使用C#,但是我现在使用的是一台新电脑,所以这次没有设置。非常感谢您的建设性答案。我很感激您抽出时间来帮助我。 - JFBN
@JFBN 这意味着您缺少它们的“命名空间”。尝试将“SearchOption”替换为“System.IO.SearchOption”,将“Directory”替换为“System.IO.Directory”。 - Avi Turner
显示剩余8条评论
4个回答

9

以下内容基本上是从此贴复制并粘贴的:

完整代码应该如下所示:

    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);

这是取消“只读”状态的方法:

// unset read-only
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attr);

如果要获取所有文件,您可以使用以下命令:

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

2

您可以通过以下方式进行检查:

FileAttributes attr = File.GetAttributes(path);
            if(attr.HasFlag( FileAttributes.ReadOnly ))
            {
             //it is readonly   
            }

1
当你写“(path);”时,我应该将其更改为实际文件路径,是吗? - JFBN

1

这篇MSDN帖子介绍了以下代码示例,用于获取文件夹权限

DirectorySecurity dSecurity = Directory.GetAccessControl(@"d:\myfolder");
foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
{
 if (rule.FileSystemRights == FileSystemRights.Read)
 {
  Console.WriteLine("Account:{0}", rule.IdentityReference.Value);
 }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接