C# 检查是否可以在特定路径中创建文件夹/文件

C# 检查是否可以在特定路径中创建文件夹/文件,c#,C#,我需要检查当前用户是否具有路径内的写入权限。这里有一个例子: 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_

我需要检查当前用户是否具有路径内的写入权限。这里有一个例子:

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");
}
已解决在:


健壮的方法是
尝试创建目录,并
捕获任何产生的异常

的文档列出了可能的异常:IOException、UnauthorizedAccessException、ArgumentException、ArgumentNullException、PathTooLongException、DirectoryNotFoundException


虽然不太可能,但在代码检查是否允许访问和实际尝试创建目录之间,权限可能发生了更改。

请参见此。您还需要检查用户是否\n符合。。。在尝试创建路径之前,路径不存在。您应该使用
path.Combine(保存路径,我的目录)而不是
save\u path+my\u dir
。它将为您处理路径。directoryseportorchar
。@NikolaiDante不工作,总是返回true试图创建目录时抛出未经授权的访问异常(使用C:\Windows作为示例)生成异常比检查访问/现有文件夹的成本更高。@Logarr只有在引发异常时才会产生成本。如果出现错误,无论如何都会引发异常,因此最好捕获并干净地处理它,而不是停止程序。所有文件I/O都应该包装在一个try..catch中,因为这是您可以合理预期会出错的事情之一。这不像在除法之前检查除数是否为零。
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");
}