我想检查用户是否能够在应用程序继续其逻辑之前写入目录。我拼凑了各种帖子的解决方案,遇到了一个我似乎无法破解的问题。我有一个我可以确认的目录设置为只读。我的问题是,一切都返回true,这表明我的方法用户能够写入目录,但是当应用程序尝试写入时,会抛出未经授权的访问异常。
代码1下面调用代码2 checkOutputDir(string output)
中的方法,然后调用代码2 hasWritePermision(string dir)
中的另一个方法进行检查。这似乎是多余的,但它是以这种方式完成的,因为稍后将在整个过程中添加额外的功能。
代码1
public string dirBrowse(string output)
{
accessCheck ac = new accessCheck();
bool writeAccess = ac.checkOutputDir(output);
if (writeAccess == false)
{
MessageBox.Show("User does not have access to the selected directory");
string msg = "Please select a directory the current useer has write access to...";
return msg;
}
else
{
var dir = output + "\\" + this.today.ToString("MM-dd-yyyy");
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
else
{
Directory.Delete(dir, true);
Directory.CreateDirectory(dir);
}
return dir;
}
}
代码2
public class accessCheck
{
// output directory
private static bool hasWritePermision(string dir)
{
bool allow = false;
bool deny = false;
DirectorySecurity acl = null;
try
{
acl = Directory.GetAccessControl(dir);
}
catch (System.IO.DirectoryNotFoundException)
{
throw new Exception("Directory Not Found");
}
if (acl == null)
{
return false;
}
AuthorizationRuleCollection arc = acl.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
if (arc == null)
{
return false;
}
foreach (FileSystemAccessRule rule in arc)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
{
continue;
}
if (rule.AccessControlType == AccessControlType.Allow)
{
allow = true;
}
else if (rule.AccessControlType == AccessControlType.Deny)
{
deny = true;
}
}
if (allow == true && deny == false)
{
return true;
}
else
{
return false;
}
}
// XREF -- Read
// staging tables -- write
public bool checkOutputDir(string output){
bool access = hasWritePermision(output);
return access ;
}
}