I would like to check if a user has the ability to write to a directory before the application continues with its logic. I have pieced together a solution from various posts and am encountering an issue I cant seem to crack. I have a directory that I can confirm is set to read only. My issue is that everything returns true which indicates to my method that the user is able to write to the directory, however when the application attempts to write it throws a unauthorized access exception which is to be expected.
Code 1 bellow calls a method in code 2 checkOutputDir(string output)
that then calls another method in code 2 hasWritePermision(string dir)
to that does the check. This may seem redundant but it is done this way because additional functionality will be added throughout this process later.
CODE 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;
}
}
CODE 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 ;
}
}