gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:03:48 26 4
gpt4 key购买 nike

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

据我所知,目录可以具有三种不同的逻辑权限状态 - 无需 UAC 提升可写、可通过 UAC 提升写入和不可写。

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

在 XP 上,这可能就像检查是否授予“允许写入”权限一样简单,但在 Vista/7 上,存在未授予此权限的目录,但使用 UAC 仍然可以执行此操作。

最佳答案

我们有一个对文件进行 WriteAccess 的方法,您可以将其调整为目录(Directory.GetAccessControl 等)

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

希望这对您有所帮助。

关于C# .NET - 如何确定目录是否可写,有或没有 UAC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3769341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com