检查是否可以在特定路径中创建文件夹/文件
本文关键字:创建 文件夹 文件 路径 是否 检查 | 更新日期: 2023-09-27 18:32:08
我需要检查当前用户是否在路径内具有写入权限。这里有一个例子:
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");
}
在这个问题中解决了:
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");
}
可靠的方法是Try
创建目录并Catch
任何结果异常。
Directory.CreateDirectory 的文档列出了可能的异常:IOException、UnauthorizedAccessException、ArgumentException、ArgumentNullException、PathTooLongException、DirectoryNotFoundException。
尽管不太可能,但代码检查是否允许访问和实际尝试创建目录之间的权限可能会发生变化。