【问题标题】:how to check if specific user having access to a shared folder location using C#如何使用 C# 检查特定用户是否有权访问共享文件夹位置
【发布时间】:2015-10-18 18:38:51
【问题描述】:

我们的客户端项目中有一个场景,客户端应用程序保存并尝试从共享文件夹位置获取文件,该位置是一个虚拟共享文件夹。但是我们一直面临着特定应用程序用户 ID 无法访问该共享文件夹的问题。因此,我们需要预先检查该共享文件夹位置上的该用户 ID 是否存在访问权限。所以考虑用 C# 或 vb.net 开发一个应用程序来检查该用户的访问权限。

【问题讨论】:

  • 请记住“共享”权限和“文件系统”权限之间的区别。您需要同时获得访问权限,而且这会变得相当复杂,具体取决于您的组织遵守既定惯例的纪律。

标签: c# .net vb.net


【解决方案1】:

我认为检查权限的最佳方式是尝试访问目录(读/写/列表)并捕获 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;
}

【讨论】:

  • 感谢 Deshdeep。但在这里我需要检查特定用户 ID 的访问权限。你能帮我解决这个问题吗?
  • 雅Deshdeep。这会很有帮助。非常感谢你:)
  • 抱歉,DeshDeep 回复晚了。它不适合我。实际上我的用户 ID 是retaillink\comrlink,但代码无法翻译。我仍在寻找解决方案。我的主要要求是不需要检查访问权限,并且该文件夹是共享生产文件夹。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多