c#测试用户是否有对文件夹的写权限

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

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

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

229883 次浏览

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

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

之前已经问过其他类似的 问题

我同意阿什的看法,应该没问题。或者,您也可以使用声明性CAS,如果它们没有访问权限,则实际上从一开始就阻止程序运行。

据我所知,我相信一些CAS特性在c# 4.0中可能不存在,不确定这是否是一个问题。

您的代码获得给定目录的DirectorySecurity,并正确处理异常(由于您没有访问安全信息)。然而,在您的示例中,您实际上并没有询问返回的对象以查看允许哪些访问—我认为您需要添加这一点。

在代码中有一个潜在的竞争条件——如果用户在检查时拥有写入文件夹的权限,但在用户实际写入文件夹之前,该权限被撤销,会发生什么情况?写入操作将抛出一个异常,您需要捕获并处理该异常。所以最初的检查是没有意义的。您也可以只执行写入并处理任何异常。这是你的情况的标准模式。

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

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

您可以尝试以下代码块检查目录是否具有写访问权限。

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

我知道现在写这篇文章有点晚了,但是您可能会发现这段代码很有用。

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

把它放到一个控制台应用程序中,看看它是否满足你的需要。

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

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

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

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

试试这个:

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

下面是CsabaS的回答的修改版本,它解释了显式的拒绝访问规则。该函数遍历目录的所有FileSystemAccessRules,并检查当前用户是否处于具有目录访问权限的角色中。如果没有找到这样的角色,或者用户处于被拒绝访问的角色,则函数返回false。要检查读权限,请传递FileSystemRights。读入函数;如果需要写权限,请传递FileSystemRights.Write。如果要检查任意用户的权限,而不是当前用户的权限,请将当前用户的权限替换为currentUser WindowsIdentity。我还建议不要依赖这样的函数来确定用户是否可以安全地使用该目录。的答案完美地解释了为什么。

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

我无法让GetAccessControl()在Windows 7上抛出一个异常,就像接受的答案中建议的那样。

我最终使用了sdd的答案的变体:

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

希望这能有所帮助。

我试过大多数方法,但都是假阳性,都是出于同样的原因。仅仅测试目录是否有可用权限是不够的,您必须检查登录用户是否是具有该权限的组的成员。为此,您需要获取用户标识,并检查它是否是包含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;
}
我也遇到了同样的问题:如何验证我是否可以在一个特定的目录中读写。我最终得到了一个简单的解决办法……实际测试一下。 下面是我简单而有效的解决方法
 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


}

希望能有所帮助!

以上解决方案很好,但对我来说,我发现这段代码简单可行。 只需要创建一个临时文件。

.

.

.

.

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

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

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

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

如果用户具有Read Permission权限为,则可以使用Authz API检查有效访问。

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

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

这应该是您所需要的全部内容,据我所知,您只需要捕获一个异常。

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