我正在制作一个自定义的SaveFileDialog。
这是目录:
C:\Windows\System32\0409
这是可读但不可写的。
我通常使用这种方式来了解它是否可读:
foreach (string i in Directory.GetDirectories(@"C:\Windows\System32\", "*", new EnumerationOptions { IgnoreInaccessible = true }))
{
////
}
但是,这种方式无法确定它是否可写。
当程序将文件写入不可写的目录时,它将引发以下错误:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access to the path 'C:\Windows\System32\0409\' is denied.
Source=System.IO.FileSystem
StackTrace:
at System.IO.FileSystem.CreateDirectory(String fullPath, Byte[] securityDescriptor)
at System.IO.Directory.CreateDirectory(String path)
at CoolDuck.Dialogs.Extract.<Window_Loaded>b__26_0() in G:\SampleProject\Test.xaml.cs:line 128
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
我不想使用try&catch
来解决此问题。我认为这不是正确的方法。
我该如何解决?谢谢。
答案 0 :(得分:6)
文件IO总是大量使用try / catch。即使您检查了ACL权限并决定可以写,也可能导致原因,系统可能会在启动前更改ACL,并且您遇到了必须要处理的权限异常。
答案 1 :(得分:-1)
这可能会对您有所帮助。当使用文件IO时,try / catch块通常用于检查此类问题。
示例方法:
public bool IsDirectoryAccessable(string dirPath, bool throwIfExc = false)
{
try
{
using (FileStream fileStream = File.Create(
Path.Combine(
dirPath,
Path.GetRandomFileName()
),
1,
FileOptions.DeleteOnClose)
)
{ }
return true;
}
catch
{
if (throwIfExc)
throw;
else
return false;
}
}