首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# .NET -如何确定目录是否可写,有没有UAC?

C# .NET -如何确定目录是否可写,有没有UAC?
EN

Stack Overflow用户
提问于 2010-09-22 20:49:28
回答 2查看 9.7K关注 0票数 8

我正在开发一个软件,它需要将文件复制到文件系统上的给定目录中。它需要在支持UAC的操作系统(Vista,7)和XP上运行。为了避免写入需要UAC提升的目录的问题,应用程序实际上启动了另一个进程,其中包含一个声明需要UAC的清单。这将生成提示,然后在用户确认时执行复制。

在我看来,一个目录可以有三种不同的逻辑权限状态--没有UAC提升的可写,有UAC提升的可写和不可写。

我的问题是:对于给定的目录,如何可靠地确定当前用户是否可以将文件复制(并可能覆盖)到该目录,如果可以,如何确定是否需要UAC提升?

在XP上,这可能和检查是否授予“允许写入”权限一样简单,但在Vista / 7上,有些目录没有授予此权限,但UAC仍然可以执行此操作。

EN

回答 2

Stack Overflow用户

发布于 2010-09-22 20:58:17

我们有一种对文件执行WriteAccess的方法,您可以将其应用于目录(Directory.GetAccessControl等)

代码语言:javascript
复制
    /// <summary> Checks for write access for the given file.
    /// </summary>
    /// <param name="fileName">The filename.</param>
    /// <returns>true, if write access is allowed, otherwise false</returns>
    public static bool WriteAccess(string fileName)
    {
        if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) != 0)
            return false;

        // Get the access rules of the specified files (user groups and user names that have access to the file)
        var rules = File.GetAccessControl(fileName).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

        // Get the identity of the current user and the groups that the user is in.
        var groups = WindowsIdentity.GetCurrent().Groups;
        string sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;

        // Check if writing to the file is explicitly denied for this user or a group the user is in.
        if (rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Deny && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData))
            return false;

        // Check if writing is allowed
        return rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Allow && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData);
    }

希望这能有所帮助。

票数 11
EN

Stack Overflow用户

发布于 2010-09-22 21:09:34

只需尝试该操作,即可处理不带提升的可写情况。当它失败的时候,你必须通过UAC提升来区分不可写和可写,这可能是很困难的。

我认为我不喜欢程序试图帮我弄清楚这一点(因为它们不可避免地会经常出错)。

我认为用这些假设设计它是安全的:

  • Administrators有时作为试用软件的受限帐户运行如果您的应用程序要对计算机进行需要UAC的侵入性更改他们想要取消,而不是elevate.
  • Elevated管理员可以写入文件(毕竟他们是管理员) ->不需要实际的->检查,检测受限令牌就足够了。
  • 用户可以使用不同的帐户提升,或者可能要求同事完成UAC必需的操作->检查受限令牌将错过这些情况。
  • 其他可恢复的事情会导致访问被拒绝,包括正在使用的文件->有时正确的做法是使用相同的受限权限重试。

因此,总的来说,我建议尝试操作AsInvoker,如果访问被拒绝,会出现一个提示,说明Windows拒绝了该操作,可能的原因是:文件正在使用,需要提升权限,需要管理员凭据,并给用户三个按钮:

带有当前credentials

  • (shield图标的
  • Cancel
  • Retry )提升权限,然后重试
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3769341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档