我正在开发一个软件,它需要将文件复制到文件系统上的给定目录中。它需要在支持UAC的操作系统(Vista,7)和XP上运行。为了避免写入需要UAC提升的目录的问题,应用程序实际上启动了另一个进程,其中包含一个声明需要UAC的清单。这将生成提示,然后在用户确认时执行复制。
在我看来,一个目录可以有三种不同的逻辑权限状态--没有UAC提升的可写,有UAC提升的可写和不可写。
我的问题是:对于给定的目录,如何可靠地确定当前用户是否可以将文件复制(并可能覆盖)到该目录,如果可以,如何确定是否需要UAC提升?
在XP上,这可能和检查是否授予“允许写入”权限一样简单,但在Vista / 7上,有些目录没有授予此权限,但UAC仍然可以执行此操作。
发布于 2010-09-22 20:58:17
我们有一种对文件执行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);
}希望这能有所帮助。
发布于 2010-09-22 21:09:34
只需尝试该操作,即可处理不带提升的可写情况。当它失败的时候,你必须通过UAC提升来区分不可写和可写,这可能是很困难的。
我认为我不喜欢程序试图帮我弄清楚这一点(因为它们不可避免地会经常出错)。
我认为用这些假设设计它是安全的:
因此,总的来说,我建议尝试操作AsInvoker,如果访问被拒绝,会出现一个提示,说明Windows拒绝了该操作,可能的原因是:文件正在使用,需要提升权限,需要管理员凭据,并给用户三个按钮:
带有当前credentials
https://stackoverflow.com/questions/3769341
复制相似问题