C# 测试用户是否对文件夹具有写权限
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1410127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Test if user has write access to a folder
提问by Chris B
I need to test if a user can write to a folder before actually attempting to do so.
我需要测试用户是否可以在实际尝试之前写入文件夹。
I've implemented the following method (in C# 2.0) that attempts to retrieve the security permissions for the folder using Directory.GetAccessControl()method.
我已经实现了以下方法(在 C# 2.0 中),该方法尝试使用Directory.GetAccessControl()方法检索文件夹的安全权限。
private bool hasWriteAccessToFolder(string folderPath)
{
try
{
// Attempt to get a list of security permissions from the folder.
// This will raise an exception if the path is read only or do not have access to view the permissions.
System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
When I was googling how to test for write access nothing like this came up and it appeared very complicated to actually test permissions in Windows. I am concerned that I am over-simplifying things and that this method is not robust, although it does seem to work.
当我在谷歌上搜索如何测试写访问权限时,没有出现类似的情况,而且在 Windows 中实际测试权限似乎非常复杂。我担心我过度简化了事情并且这种方法并不可靠,尽管它似乎确实有效。
Will my method to test if the current user has write access work correctly?
我的测试当前用户是否具有写访问权限的方法可以正常工作吗?
采纳答案by Ash
That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception maybe an issue.
这是在 C# 中检查文件夹访问的完全有效的方法。它可能会失败的唯一地方是,如果您需要在一个紧密循环中调用它,其中异常的开销可能是一个问题。
回答by Darin Dimitrov
IMHO the only 100% reliable way to test if you can write to a directory is to actually write to it and eventually catch exceptions.
恕我直言,测试是否可以写入目录的唯一 100% 可靠方法是实际写入并最终捕获异常。
回答by Ian
I agree with Ash, that should be fine. Alternatively you could use declarative CAS and actually prevent the program from running in the first place if they don't have access.
我同意 Ash 的观点,应该没问题。或者,您可以使用声明性 CAS 并在他们没有访问权限的情况下首先阻止程序运行。
I believe some of the CAS features may not be present in C# 4.0 from what I've heard, not sure if that might be an issue or not.
据我所知,我相信 C# 4.0 中可能不存在某些 CAS 功能,不确定这是否是一个问题。
回答by Vinay Sajip
Your code gets the DirectorySecurity
for a given directory, and handles an exception (due to your not having access to the security info) correctly. However, in your sample you don't actually interrogate the returned object to see what access is allowed - and I think you need to add this in.
您的代码获取DirectorySecurity
给定目录的 ,并正确处理异常(由于您无法访问安全信息)。但是,在您的示例中,您实际上并未询问返回的对象以查看允许访问的内容 - 我认为您需要将其添加进去。
回答by Vinay Sajip
You have a potential race condition in your code--what happens if the user has permissions to write to the folder when you check, but before the user actually writes to the folder this permission is withdrawn? The write will throw an exception which you will need to catch and handle. So the initial check is pointless. You might as well just do the write and handle any exceptions. This is the standard pattern for your situation.
您的代码中存在潜在的竞争条件——如果在您检查时用户具有写入文件夹的权限,但在用户实际写入文件夹之前,此权限已被撤销,会发生什么情况?写入将抛出一个异常,您需要捕获并处理该异常。所以最初的检查是没有意义的。您也可以只进行写入并处理任何异常。这是您的情况的标准模式。
回答by Vinay Sajip
http://www.codeproject.com/KB/files/UserFileAccessRights.aspx
http://www.codeproject.com/KB/files/UserFileAccessRights.aspx
Very usefull Class, check for improved version in messages bellow.
非常有用的类,请在下面的消息中检查改进版本。
回答by RockWorld
You can try following code block to check if the directory is having Write Access. It checks the FileSystemAccessRule.
您可以尝试以下代码块来检查目录是否具有写访问权限。它检查 FileSystemAccessRule。
string directoryPath = "C:\XYZ"; //folderBrowserDialog.SelectedPath;
bool isWriteAccess = false;
try
{
AuthorizationRuleCollection collection =
Directory.GetAccessControl(directoryPath)
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule rule in collection)
{
if (rule.AccessControlType == AccessControlType.Allow)
{
isWriteAccess = true;
break;
}
}
}
catch (UnauthorizedAccessException ex)
{
isWriteAccess = false;
}
catch (Exception ex)
{
isWriteAccess = false;
}
if (!isWriteAccess)
{
//handle notifications
}
回答by Duncan Howe
I appreciate that this is a little late in the day for this post, but you might find this bit of code useful.
我很感激这篇文章的时间有点晚,但您可能会发现这段代码很有用。
string path = @"c:\temp";
string NtAccountName = @"MyDomain\MyUserOrGroup";
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
//If we find one that matches the identity we are looking for
if (rule.IdentityReference.Value.Equals(NtAccountName,StringComparison.CurrentCultureIgnoreCase))
{
var filesystemAccessRule = (FileSystemAccessRule)rule;
//Cast to a FileSystemAccessRule to check for access rights
if ((filesystemAccessRule.FileSystemRights & FileSystemRights.WriteData)>0 && filesystemAccessRule.AccessControlType != AccessControlType.Deny)
{
Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path));
}
else
{
Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path));
}
}
}
Console.ReadLine();
Drop that into a Console app and see if it does what you need.
将其放入控制台应用程序,看看它是否满足您的需求。
回答by priit
public bool IsDirectoryWritable(string dirPath, bool throwIfFails = false)
{
try
{
using (FileStream fs = File.Create(
Path.Combine(
dirPath,
Path.GetRandomFileName()
),
1,
FileOptions.DeleteOnClose)
)
{ }
return true;
}
catch
{
if (throwIfFails)
throw;
else
return false;
}
}
回答by Mort
Simply trying to access the file in question isn't necessarily enough. The test will run with the permissions of the user running the program - Which isn't necessarily the user permissions you want to test against.
仅仅尝试访问有问题的文件是不够的。测试将在运行程序的用户的权限下运行 - 这不一定是您要测试的用户权限。