[英]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.