[英]Issues checking if folder exists
我有以下创建文件夹的C#代码:
if (!Directory.Exists(strCreatePath))
{
Directory.CreateDirectory(strCreatePath);
}
它有效,除非我有一个文件夹: C:\\\\Users\\\\UserName\\\\Desktop
Directory.Exists
返回false
,这不是真的,但是然后Directory.CreateDirectory
抛出异常: Access to the path 'C:\\\\Users\\\\UserName\\\\Desktop' is denied.
。
任何想法如何防止除了捕获这样的异常,我宁愿避免?
您应首先检查目录是否为ReadOnly
:
bool isReadOnly = ((File.GetAttributes(strCreatePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
if(!isReadOnly)
{
try
{
Directory.CreateDirectory(strCreatePath);
} catch (System.UnauthorizedAccessException unauthEx)
{
// still the same eception ?!
Console.Write(unauthEx.ToString());
}
catch (System.IO.IOException ex)
{
Console.Write(ex.ToString());
}
}
谢谢大家。 这是我如何能够处理它而不会抛出不必要的例外:
[DllImportAttribute("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes);
void createFolder(string strCreatePath)
{
if (!CreateDirectory(strCreate, IntPtr.Zero))
{
int nOSError = Marshal.GetLastWin32Error();
if (nOSError != 183) //ERROR_ALREADY_EXISTS
{
//Error
throw new System.ComponentModel.Win32Exception(nOSError);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.