我需要检查当前用户是否在路径中具有写权限。这是一个例子:
string save_path = @"C:\Windows\somefolder";
string my_dir = Path.DirectorySeparatorChar + "foobar";
//check if specific path are valid
if (!Directory.Exists(save_path)) { return; }
if (Directory.Exists(save_path + my_dir)) { return; }
if (canWriteOnPath(save_path)) {
Directory.CreateDirectory(save_path + my_dir);
} else {
//You are not allowed to save here OR not are launching this application as "administrator"
Directory.CreateDirectory(@"C:\Users\contoso\Documents\foobar");
}
this question中的已解决:
CurrentUserSecurity cus = new CurrentUserSecurity();
bool flag = cus.HasAccess(new DirectoryInfo(@"C:\Windows"), FileSystemRights.Write);
if (flag) {
//yes create that folder
Directory.CreateDirectory(Path.Combine(save_path, my_dir));
} else {
//NO YOU CANT
Directory.CreateDirectory(@"C:\Users\contoso\Documents\foobar");
}
答案 0 :(得分:2)
健壮的方法是Try
创建目录,Catch
任何结果异常。
Directory.CreateDirectory的文档列出了可能的异常:IOException,UnauthorizedAccessException,ArgumentException,ArgumentNullException,PathTooLongException,DirectoryNotFoundException。
虽然不太可能,但可能在您的代码检查允许访问和实际尝试创建目录之间权限发生了更改。