【问题标题】:C# Test if user has write access to a folderC#测试用户是否对文件夹有写权限
【发布时间】:2010-11-27 11:07:36
【问题描述】:

在实际尝试之前,我需要测试用户是否可以写入文件夹。

我已经实现了以下方法(在 C# 2.0 中),它尝试使用 Directory.GetAccessControl() 方法检索文件夹的安全权限。

private bool hasWriteAccessToFolder(string folderPath)
{
    try
    {
        // Attempt to get a list of security permissions from the folder. 
        // This will raise an exception if the path is read only or do not have access to view the permissions. 
        System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
        return true;
    }
    catch (UnauthorizedAccessException)
    {
        return false;
    }
}

当我在谷歌上搜索如何测试写访问权限时,没有出现类似的情况,在 Windows 中实际测试权限似乎非常复杂。我担心我过度简化了事情,而且这种方法并不可靠,尽管它似乎确实有效。

我测试当前用户是否有写权限的方法能正常工作吗?

【问题讨论】:

  • 没有访问权限view真的和不允许写一样吗?

标签: c# permissions directory


【解决方案1】:
public bool IsDirectoryWritable(string dirPath, bool throwIfFails = false)
{
    try
    {
        using (FileStream fs = File.Create(
            Path.Combine(
                dirPath, 
                Path.GetRandomFileName()
            ), 
            1,
            FileOptions.DeleteOnClose)
        )
        { }
        return true;
    }
    catch
    {
        if (throwIfFails)
            throw;
        else
            return false;
    }
}

【讨论】:

  • 此答案将捕获尝试写入文件时可能发生的所有异常,而不仅仅是权限违规。
  • @G.Y,string tempFileName = Path.GetRandomFileName();,显然
  • @Matt,但是,无论失败的原因如何,这都能准确回答“目录是否可写”的问题。您宁愿回答“为什么我无法写入目录”。 :)
  • 我收到此代码的误报。 File.Create() 运行正常(如果您更改最后一个选项,则会留下一个临时文件),即使执行用户没有写入该文件夹的权限。真的很奇怪 - 花了一个小时试图找出原因,但我很难过。
  • 从我在下面尝试过的所有替代方案(和引用的链接)中 - 这是唯一一个可靠工作的方案。
【解决方案2】:

感谢这篇文章的时间有点晚,但您可能会发现这段代码很有用。

string path = @"c:\temp";
string NtAccountName = @"MyDomain\MyUserOrGroup";

DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));

//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
    //If we find one that matches the identity we are looking for
    if (rule.IdentityReference.Value.Equals(NtAccountName,StringComparison.CurrentCultureIgnoreCase))
    {
        var filesystemAccessRule = (FileSystemAccessRule)rule;

        //Cast to a FileSystemAccessRule to check for access rights
        if ((filesystemAccessRule.FileSystemRights & FileSystemRights.WriteData)>0 && filesystemAccessRule.AccessControlType != AccessControlType.Deny)
        {
            Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path));
        }
        else
        {
            Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path));
        }
    }
}

Console.ReadLine();

将它放到控制台应用程序中,看看它是否满足您的需求。

【讨论】:

  • 正中目标!对我有很大帮助!
  • 我在调用GetAccessControl 时遇到异常,但我的软件实际上能够写入我正在查看的目录.. ?
  • 您需要添加对 FileSystemAccessRule 类型的检查。如果是拒绝规则,您将错误地将其报告为可写。
  • 我正在尝试使用它。又发现一个问题。如果权限仅分配给组而不是特定用户,这将错误地报告他们没有写入权限。例如,授予“Authenticated users”的写入权限
  • 这给了我PrivilegeNotHeldException 以正常权限运行时
【解决方案3】:

这是在 C# 中检查文件夹访问的一种非常有效的方法。唯一可能失败的地方是,如果您需要在一个紧密的循环中调用它,而异常的开销可能是个问题。

之前有其他similarquestions问过。

【讨论】:

  • 有趣的是,我在另一个选项卡中打开了其他问题之一,但没有看到有关 DirectorySecurity 的答案,请教我阅读所有的答案,而不仅仅是接受的答案;-)
  • 在Windows中使用长路径不也会掉下来吗?
  • 这不会告诉你是否有写权限,它只会告诉你是否可以查看该文件夹的权限。此外,您可能可以写入但无法查找权限。
【解决方案4】:

我尝试了其中的大部分,但它们都给出了误报,所有这些都是出于相同的原因.. 测试目录的可用权限是不够的,您必须检查登录用户是否是组的成员有那个权限。为此,您获取用户身份,并检查它是否是包含 FileSystemAccessRule IdentityReference 的组的成员。我已经测试过了,完美无瑕..

    /// <summary>
    /// Test a directory for create file access permissions
    /// </summary>
    /// <param name="DirectoryPath">Full path to directory </param>
    /// <param name="AccessRight">File System right tested</param>
    /// <returns>State [bool]</returns>
    public static bool DirectoryHasPermission(string DirectoryPath, FileSystemRights AccessRight)
    {
        if (string.IsNullOrEmpty(DirectoryPath)) return false;

        try
        {
            AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
            WindowsIdentity identity = WindowsIdentity.GetCurrent();

            foreach (FileSystemAccessRule rule in rules)
            {
                if (identity.Groups.Contains(rule.IdentityReference))
                {
                    if ((AccessRight & rule.FileSystemRights) == AccessRight)
                    {
                        if (rule.AccessControlType == AccessControlType.Allow)
                            return true;
                    }
                }
            }
        }
        catch { }
        return false;
    }

【讨论】:

  • 谢谢约翰,在我使用您的代码再次检查用户组规则之前,我也有误报!
  • 我必须为 identity.Owner == rule.IdentityReference 添加额外的检查,因为我有一个用户授予访问权限但不属于任何组,例如用于服务的专用本地帐户
  • AccessControlType 拒绝优先于允许,因此要完全彻底地拒绝访问权限的规则也应该检查,并且在检查拒绝类型时应该是(AccessRight &amp; rule.FileSystemRights) &gt; 0,因为任何子访问类型都被拒绝这是AccessRight 的一部分意味着您没有对AccessRight 的完全访问权限
  • 正如上面提到的grinder22,我需要改变; if (identity.Groups.Contains(rule.IdentityReference)) 到 if (identity.Groups.Contains(rule.IdentityReference) || identity.Owner.Equals(rule.IdentityReference)) 因为我有一个用户可以访问但不是t 在任何组中。
  • @NickeManarin 可能存在允许访问的规则,但也可能存在拒绝访问的不同规则,并且拒绝覆盖允许,因此仅跳过拒绝规则是不够的。另外,如果你想要读写的访问权限,但是有拒绝写访问的规则,那么即使有允许读写的规则,也会阻止完全的读写访问。
【解决方案5】:

恕我直言,测试您是否可以写入目录的唯一 100% 可靠方法是实际写入并最终捕获异常。

【讨论】:

    【解决方案6】:

    例如对于所有用户 (Builtin\Users),此方法工作正常 - 享受。

    public static bool HasFolderWritePermission(string destDir)
    {
       if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
       try
       {
          DirectorySecurity security = Directory.GetAccessControl(destDir);
          SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
          foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
          {
              if(rule.IdentityReference == users)
              {
                 FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
                 if(rights.AccessControlType == AccessControlType.Allow)
                 {
                        if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
                 }
              }
           }
           return false;
        }
        catch
        {
            return false;
        }
    }
    

    【讨论】:

      【解决方案7】:

      试试这个:

      try
      {
          DirectoryInfo di = new DirectoryInfo(path);
          DirectorySecurity acl = di.GetAccessControl();
          AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
      
          WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
          WindowsPrincipal principal = new WindowsPrincipal(currentUser);
          foreach (AuthorizationRule rule in rules)
          {
              FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
              if (fsAccessRule == null)
                  continue;
      
              if ((fsAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0)
              {
                  NTAccount ntAccount = rule.IdentityReference as NTAccount;
                  if (ntAccount == null)
                  {
                      continue;
                  }
      
                  if (principal.IsInRole(ntAccount.Value))
                  {
                      Console.WriteLine("Current user is in role of {0}, has write access", ntAccount.Value);
                      continue;
                  }
                  Console.WriteLine("Current user is not in role of {0}, does not have write access", ntAccount.Value);                        
              }
          }
      }
      catch (UnauthorizedAccessException)
      {
          Console.WriteLine("does not have write access");
      }
      

      【讨论】:

      • 如果我没记错的话,这很接近但并不完全存在——它忽略了fsAccessRule.AccessControlType 可能是AccessControlType.Deny 的事实。
      • 这在我的 Win7 开发机器上为我工作,但在 Win10 上失败(对于测试人员和我自己的测试机器)。 ssds 的修改(见下文)似乎修复了它。
      【解决方案8】:

      您的代码获取给定目录的DirectorySecurity,并正确处理异常(由于您无权访问安全信息)。但是,在您的示例中,您实际上并没有询问返回的对象以查看允许的访问权限 - 我认为您需要添加它。

      【讨论】:

      • +1 - 我刚刚遇到了这个问题,在调用 GetAccessControl 时未引发异常,但在尝试写入同一目录时却遇到未经授权的异常。
      【解决方案9】:

      这是CsabaS's answer 的修改版本,它解释了明确的拒绝访问规则。该函数遍历目录的所有 FileSystemAccessRules,并检查当前用户是否处于有权访问目录的角色中。如果未找到此类角色或用户处于拒绝访问的角色中,则该函数返回 false。要检查读取权限,请将 FileSystemRights.Read 传递给函数;对于写权限,传递 FileSystemRights.Write。如果要检查任意用户的权限而不是当前用户的权限,请将 currentUser WindowsIdentity 替换为所需的 WindowsIdentity。我还建议不要依赖这样的函数来确定用户是否可以安全地使用该目录。 This 回答完美解释了原因。

          public static bool UserHasDirectoryAccessRights(string path, FileSystemRights accessRights)
          {
              var isInRoleWithAccess = false;
      
              try
              {
                  var di = new DirectoryInfo(path);
                  var acl = di.GetAccessControl();
                  var rules = acl.GetAccessRules(true, true, typeof(NTAccount));
      
                  var currentUser = WindowsIdentity.GetCurrent();
                  var principal = new WindowsPrincipal(currentUser);
                  foreach (AuthorizationRule rule in rules)
                  {
                      var fsAccessRule = rule as FileSystemAccessRule;
                      if (fsAccessRule == null)
                          continue;
      
                      if ((fsAccessRule.FileSystemRights & accessRights) > 0)
                      {
                          var ntAccount = rule.IdentityReference as NTAccount;
                          if (ntAccount == null)
                              continue;
      
                          if (principal.IsInRole(ntAccount.Value))
                          {
                              if (fsAccessRule.AccessControlType == AccessControlType.Deny)
                                  return false;
                              isInRoleWithAccess = true;
                          }
                      }
                  }
              }
              catch (UnauthorizedAccessException)
              {
                  return false;
              }
              return isInRoleWithAccess;
          }
      

      【讨论】:

      • Csaba 的代码在 Windows 10 上对我来说是失败的(但在我的 Win7 开发机器上很好)。以上似乎解决了这个问题。
      【解决方案10】:

      上述解决方案很好,但对我来说,我发现这段代码简单可行。 只需创建一个临时文件。如果创建了文件,则其平均用户具有写入权限。

              public static bool HasWritePermission(string tempfilepath)
              {
                  try
                  {
                      System.IO.File.Create(tempfilepath + "temp.txt").Close();
                      System.IO.File.Delete(tempfilepath + "temp.txt");
                  }
                  catch (System.UnauthorizedAccessException ex)
                  {
      
                      return false;
                  }
      
                  return true;
              }
      

      【讨论】:

      • 不错!但有一件事是该用户可能拥有Create 权限但没有Delete 在这种情况下,即使用户确实拥有写入权限,这也会返回false。
      • 最方便的编码答案 :) 我也只使用这个,但是,当有大量并发请求时,如此多的读/写可能会降低性能,因此在这些情况下,您可以使用访问控制方法在其他答案中给出。
      • 使用Path.Combine,例如Path.Combine(tempfilepath, "temp.txt")。
      • 临时文件名最好使用 GUID。
      【解决方案11】:

      您可以尝试以下代码块来检查目录是否具有写入权限。 它检查 FileSystemAccessRule。

      string directoryPath = "C:\\XYZ"; //folderBrowserDialog.SelectedPath;
      bool isWriteAccess = false;
      try
      {
          AuthorizationRuleCollection collection =
              Directory.GetAccessControl(directoryPath)
                  .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
          foreach (FileSystemAccessRule rule in collection)
          {
              if (rule.AccessControlType == AccessControlType.Allow)
              {
                  isWriteAccess = true;
                  break;
              }
          }
      }
      catch (UnauthorizedAccessException ex)
      {
          isWriteAccess = false;
      }
      catch (Exception ex)
      {
          isWriteAccess = false;
      }
      if (!isWriteAccess)
      {
          //handle notifications 
      }
      

      【讨论】:

        【解决方案12】:

        您的代码中存在潜在的竞争条件 - 如果在您检查时用户有权写入文件夹,但在用户实际写入文件夹之前,此权限被撤销,会发生什么情况?写入将引发您需要捕获和处理的异常。所以最初的检查是没有意义的。您不妨只进行写入并处理任何异常。这是适合您情况的标准模式。

        【讨论】:

        • 如何让用户知道他们在配置对话框中选择的默认位置没有存储接收到的内容文件的适当权限?当然,在稍后的某个时间点(0-999 天的时间),当实际收到内容文件时,您无论如何都必须处理异常,因为权限可能已更改,但最好在用户设置初始配置时警告用户。
        【解决方案13】:

        http://www.codeproject.com/KB/files/UserFileAccessRights.aspx

        非常有用的类,在下面的消息中检查改进版本。

        【讨论】:

          【解决方案14】:

          仅仅尝试访问相关文件是不够的。测试将以运行程序的用户的权限运行 - 这不一定是您要测试的用户权限。

          【讨论】:

            【解决方案15】:

            我同意 Ash 的观点,那应该没问题。或者,您可以使用声明性 CAS,如果他们无权访问,则实际上阻止程序运行。

            据我所知,我认为 C# 4.0 中可能不存在某些 CAS 功能,不确定这是否是个问题。

            【讨论】:

              【解决方案16】:

              我无法让 GetAccessControl() 按照已接受答案中的建议在 Windows 7 上引发异常。

              我最终使用了sdds's 答案的变体:

                      try
                      {
                          bool writeable = false;
                          WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                          DirectorySecurity security = Directory.GetAccessControl(pstrPath);
                          AuthorizationRuleCollection authRules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
              
                          foreach (FileSystemAccessRule accessRule in authRules)
                          {
              
                              if (principal.IsInRole(accessRule.IdentityReference as SecurityIdentifier))
                              {
                                  if ((FileSystemRights.WriteData & accessRule.FileSystemRights) == FileSystemRights.WriteData)
                                  {
                                      if (accessRule.AccessControlType == AccessControlType.Allow)
                                      {
                                          writeable = true;
                                      }
                                      else if (accessRule.AccessControlType == AccessControlType.Deny)
                                      {
                                          //Deny usually overrides any Allow
                                          return false;
                                      }
              
                                  } 
                              }
                          }
                          return writeable;
                      }
                      catch (UnauthorizedAccessException)
                      {
                          return false;
                      }
              

              希望这会有所帮助。

              【讨论】:

                【解决方案17】:

                我遇到了同样的问题:如何验证我是否可以在特定目录中读/写。我最终得到了一个简单的解决方案来......实际测试它。 这是我的简单但有效的解决方案。

                 class Program
                {
                
                    /// <summary>
                    /// Tests if can read files and if any are present
                    /// </summary>
                    /// <param name="dirPath"></param>
                    /// <returns></returns>
                    private genericResponse check_canRead(string dirPath)
                    {
                        try
                        {
                            IEnumerable<string> files = Directory.EnumerateFiles(dirPath);
                            if (files.Count().Equals(0))
                                return new genericResponse() { status = true, idMsg = genericResponseType.NothingToRead };
                
                            return new genericResponse() { status = true, idMsg = genericResponseType.OK };
                        }
                        catch (DirectoryNotFoundException ex)
                        {
                
                            return new genericResponse() { status = false, idMsg = genericResponseType.ItemNotFound };
                
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                
                            return new genericResponse() { status = false, idMsg = genericResponseType.CannotRead };
                
                        }
                
                    }
                
                    /// <summary>
                    /// Tests if can wirte both files or Directory
                    /// </summary>
                    /// <param name="dirPath"></param>
                    /// <returns></returns>
                    private genericResponse check_canWrite(string dirPath)
                    {
                
                        try
                        {
                            string testDir = "__TESTDIR__";
                            Directory.CreateDirectory(string.Join("/", dirPath, testDir));
                
                            Directory.Delete(string.Join("/", dirPath, testDir));
                
                
                            string testFile = "__TESTFILE__.txt";
                            try
                            {
                                TextWriter tw = new StreamWriter(string.Join("/", dirPath, testFile), false);
                                tw.WriteLine(testFile);
                                tw.Close();
                                File.Delete(string.Join("/", dirPath, testFile));
                
                                return new genericResponse() { status = true, idMsg = genericResponseType.OK };
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                
                                return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteFile };
                
                            }
                
                
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                
                            return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteDir };
                
                        }
                    }
                
                
                }
                
                public class genericResponse
                {
                
                    public bool status { get; set; }
                    public genericResponseType idMsg { get; set; }
                    public string msg { get; set; }
                
                }
                
                public enum genericResponseType
                {
                
                    NothingToRead = 1,
                    OK = 0,
                    CannotRead = -1,
                    CannotWriteDir = -2,
                    CannotWriteFile = -3,
                    ItemNotFound = -4
                
                }
                

                希望对你有帮助!

                【讨论】:

                  【解决方案18】:

                  这应该是你所需要的,据我所知,你只需要捕获一个异常。

                  private static readonly byte[] TestArray = new byte[]{
                      69, 70, 71, 72
                  };
                  
                  private static bool IsFolderAccessible(string path) {
                      var temp_path = Path.Combine(path, Path.GetRandomFileName());
                  
                      try {
                          using (var file = File.Create(temp_path, TestArray.Length, FileOptions.DeleteOnClose)) {
                              file.Write(TestArray, 0, TestArray.Length);
                          }
                  
                          return true;
                      } catch (UnauthorizedAccessException ex) {
                          Log.Warn($"Error accessing file {temp_path}", ex);
                  
                          return false;
                      }
                  }
                  

                  【讨论】:

                    【解决方案19】:

                    这里的大多数答案都不检查写访问。它只是检查用户/组是否可以“读取权限”(读取文件/目录的 ACE 列表)。

                    另外遍历 ACE 并检查它是否与安全标识符匹配也不起作用,因为用户可能是他可能获得/失去权限的组的成员。比这更糟糕的是嵌套组。

                    我知道这是一个旧线程,但现在任何人都有更好的方法。

                    如果用户具有读取权限,则可以使用 Authz API 来检查有效访问。

                    https://docs.microsoft.com/en-us/windows/win32/secauthz/using-authz-api

                    https://docs.microsoft.com/en-us/windows/win32/secauthz/checking-access-with-authz-api

                    【讨论】:

                      猜你喜欢
                      • 2010-10-18
                      • 1970-01-01
                      • 2014-03-27
                      • 2011-06-06
                      • 2011-08-10
                      • 2014-08-14
                      • 1970-01-01
                      • 1970-01-01
                      • 2011-04-07
                      相关资源
                      最近更新 更多