簡體   English   中英

檢查文件夾是否存在的問題

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

任何想法如何防止除了捕獲這樣的異常,我寧願避免?

根據文件

如果您沒有對目錄的最低只讀權限,則Exists方法將返回false。

所以你所看到的行為是預料之中的。 即使您確實檢查了權限,這也是一個合理的例外,所以最好的辦法是簡單地處理異常。

您應首先檢查目錄是否為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM