繁体   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