我们的客户端项目中有一个场景,客户端应用程序保存并尝试从共享文件夹位置(虚拟共享文件夹)中获取文件。但是我们一直面临着特定应用程序用户ID无法访问该共享文件夹的问题。因此,我们需要提前检查是否存在该共享文件夹位置上该用户ID的访问权限。因此,考虑在C#或vb.net中开发应用程序以检查该用户访问权限。
答案 0 :(得分:2)
我认为最好检查权限的方法是尝试访问目录(读/写/列表)&捕获UnauthorizedAccessException。
如果要检查权限,以下代码应满足您的需要。您需要阅读Access Rules
目录。
private bool DirectoryCanListFiles(string folder)
{
bool hasAccess = false;
//Step 1. Get the userName for which, this app domain code has been executing
string executingUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
NTAccount acc = new NTAccount(executingUser);
SecurityIdentifier secId = acc.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
DirectorySecurity dirSec = Directory.GetAccessControl(folder);
//Step 2. Get directory permission details for each user/group
AuthorizationRuleCollection authRules = dirSec.GetAccessRules(true, true, typeof(SecurityIdentifier));
foreach (FileSystemAccessRule ar in authRules)
{
if (secId.CompareTo(ar.IdentityReference as SecurityIdentifier) == 0)
{
var fileSystemRights = ar.FileSystemRights;
Console.WriteLine(fileSystemRights);
//Step 3. Check file system rights here, read / write as required
if (fileSystemRights == FileSystemRights.Read ||
fileSystemRights == FileSystemRights.ReadAndExecute ||
fileSystemRights == FileSystemRights.ReadData ||
fileSystemRights == FileSystemRights.ListDirectory)
{
hasAccess = true;
}
}
}
return hasAccess;
}