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

我已经实现了以下方法(在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中测试权限看起来非常复杂。我担心我过于简化了事情,这个方法并不健壮,尽管它似乎确实有效。

我测试当前用户是否具有写访问权限的方法是否正确?


当前回答

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

之前也有人问过类似的问题。

其他回答

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

仅仅尝试访问有问题的文件是不够的。测试将在运行程序的用户的权限下运行——这并不一定是您想要测试的用户权限。

例如,对于所有用户(内置用户),此方法工作良好-享受。

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

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

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

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

之前也有人问过类似的问题。