【问题标题】:Folder (Directory) Read Only?文件夹(目录)只读?
【发布时间】:2016-02-11 10:54:29
【问题描述】:

我有一个名为 FolderHelper 的类,其方法为 ReadOnly - 目的是检查指定目录是否为只读并返回布尔值 true 或 false。

public static bool ReadOnly(string path)
{
    DirectoryInfo directoryInfo = new DirectoryInfo(path);

    if (directoryInfo.Attributes.HasFlag(FileAttributes.ReadOnly))
    {
        return true;
    }
    return false;
}

我已将目录设置为只读,但该方法总是返回 false - 任何人都可以提出任何理由吗?

【问题讨论】:

  • 目录不能在 Windows 文件系统上设置为只读。
  • 仔细查看read-only checkbox

标签: c# .net directoryinfo


【解决方案1】:

只读标志只能应用于文件,不能应用于目录。如果您尝试使用 Windows 资源管理器在目录上设置此标志 - 您最终会得到相同的结果 - 标志将不会设置到目录,但可以设置/取消设置到它包含的文件。由于标志不能设置为目录 - 显然你不能从目录中获取它。

您可能需要检查此目录的写入权限,以确定用户是否可以创建/修改此目录中包含的文件。可以使用Directory.GetAccessControl查看。

【讨论】:

【解决方案2】:

在另一篇 stackOverflow 文章中找到了这个,可能这就是你需要做的

C# Test if user has write access to a folder

 public bool IsReadOnly(string dirPath)
    {
        try
        {
            using (FileStream fs = File.Create(
                Path.Combine(
                    dirPath, 
                    Path.GetRandomFileName()
                ), 
                1,
                FileOptions.DeleteOnClose)
            )
            { }
            return false;
        }
        catch
        {

                return true;
        }
    }

【讨论】:

  • @downvoter...请解释一下,以便我改进我的答案
猜你喜欢
  • 2015-04-02
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 2013-02-28
  • 2013-06-20
  • 1970-01-01
相关资源
最近更新 更多