【问题标题】:C# Directory.GetDirectories - how to workaround UnauthorizedAccessException?C# Directory.GetDirectories - 如何解决 UnauthorizedAccessException?
【发布时间】:2012-11-16 13:11:54
【问题描述】:

当我尝试使用 Directory.GetDirectories(systemVolumePath) 访问系统卷时,我的应用会抛出 UnauthorizedAccessException。美好的。我在这里看到了所有使用 try catch 的答案 - 这不是我想要的。

如何在具有足够权限访问所有文件夹的帐户下运行我的应用程序?

谢谢

【问题讨论】:

标签: c# io


【解决方案1】:

我已经成功使用 runas.exe 工具来做到这一点。

runas.exe /savecred /user:yourusernamehere my_app_that_needs_permissions.exe

这将在当前桌面环境中运行应用程序,但使用其他用户的配置文件和权限,因此文件访问(包括创建文件)将使用该用户的凭据进行。

这样做的一个有趣的副作用是,您的应用程序创建的任何文件都将作为所有者创建为其他用户,而您的当前用户可能没有访问它们所需的权限。

这是世界多用户环境的一次有趣的短途旅行。

如果您想通过自己的代码执行此操作,这些 SO 帖子似乎涵盖了它:

Launch a process under another user's credentials

Using Process.Start() to start a process as a different user from within a Windows Service

【讨论】:

    【解决方案2】:

    据我所知,您无法“解决”安全问题。你能做的就是需要权限。

    您必须要求用户提升权限,才能让您的代码以所需的权限运行。

    在 .NET 中,您可以使用 Declarative SyntaxImperative Syntax 来执行此操作。

    这是一个来自 Microsoft 的示例,它使用命令式语法来要求对单个文件夹的权限:

    FileIOPermission permFileIO =
    new FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\\Temp");
    try 
    {
        // Demand the permission to access the C:\Temp folder.
        permFileIO.Demand();
        resultText.Append("The demand for permission to access the C:\\Temp folder succeeded.\n\n");
    }
    catch (SecurityException se)
    {
        resultText.Append("The demand for permission to access the C:\\Temp folder failed.\nException message: ");
        resultText.Append(se.Message);
        resultText.Append("\n\n");
    }
    

    【讨论】:

      【解决方案3】:

      要访问这些目录,您需要在 LocalSystem 帐户下运行,这不是您应该轻易考虑的事情。

      PSExec 将在适合您的使用场景的情况下帮助您实现所需。

      【讨论】:

        猜你喜欢
        • 2010-11-02
        • 1970-01-01
        • 2015-10-26
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 1970-01-01
        相关资源
        最近更新 更多