在我的 .NET 2.0 应用程序中,我需要检查是否存在足够的权限来创建文件并将文件写入目录。为此,我有以下函数尝试创建一个文件并向其写入一个字节,然后删除自身以测试是否存在权限。
我认为最好的检查方法是实际尝试并捕获发生的任何异常。不过,我对一般的异常捕获不是特别满意,那么有没有更好的或者更容易接受的方法呢?
private const string TEMP_FILE = "\\tempFile.tmp";
/// <summary>
/// Checks the ability to create and write to a file in the supplied directory.
/// </summary>
/// <param name="directory">String representing the directory path to check.</param>
/// <returns>True if successful; otherwise false.</returns>
private static bool CheckDirectoryAccess(string directory)
{
bool success = false;
string fullPath = directory + TEMP_FILE;
if (Directory.Exists(directory))
{
try
{
using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew,
FileAccess.Write))
{
fs.WriteByte(0xff);
}
if (File.Exists(fullPath))
{
File.Delete(fullPath);
success = true;
}
}
catch (Exception)
{
success = false;
}
}
最佳答案
Directory.GetAccessControl(path)
完成您的要求。
public static bool HasWritePermissionOnDir(string path)
{
var writeAllow = false;
var writeDeny = false;
var accessControlList = Directory.GetAccessControl(path);
if (accessControlList == null)
return false;
var accessRules = accessControlList.GetAccessRules(true, true,
typeof(System.Security.Principal.SecurityIdentifier));
if (accessRules ==null)
return false;
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
continue;
if (rule.AccessControlType == AccessControlType.Allow)
writeAllow = true;
else if (rule.AccessControlType == AccessControlType.Deny)
writeDeny = true;
}
return writeAllow && !writeDeny;
}
(FileSystemRights.Write & rights) == FileSystemRights.Write
正在使用一种叫做“Flags”的东西,顺便说一句,如果你不知道它是什么,你应该仔细阅读 :)
关于c# - 检查 .NET 中的目录和文件写入权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1281620/