简体   繁体   English

检查文件夹是否存在的问题

[英]Issues checking if folder exists

I have the following C# code that creates a folder: 我有以下创建文件夹的C#代码:

if (!Directory.Exists(strCreatePath))
{
    Directory.CreateDirectory(strCreatePath);
}

It works, except if I have a folder as such: C:\\\\Users\\\\UserName\\\\Desktop the Directory.Exists returns false , which is not true, but then Directory.CreateDirectory throws an exception: Access to the path 'C:\\\\Users\\\\UserName\\\\Desktop' is denied. 它有效,除非我有一个文件夹: C:\\\\Users\\\\UserName\\\\Desktop Directory.Exists返回false ,这不是真的,但是然后Directory.CreateDirectory抛出异常: Access to the path 'C:\\\\Users\\\\UserName\\\\Desktop' is denied. .

Any idea how to prevent that apart from catching such exception, which I prefer to avoid? 任何想法如何防止除了捕获这样的异常,我宁愿避免?

According to the docs : 根据文件

If you do not have at a minimum read-only permission to the directory, the Exists method will return false. 如果您没有对目录的最低只读权限,则Exists方法将返回false。

So the behavior you are seeing is expected. 所以你所看到的行为是预料之中的。 This is a legitimate exception that can happen even if you do check for permissions, so your best bet is to simply handle the exception. 即使您确实检查了权限,这也是一个合理的例外,所以最好的办法是简单地处理异常。

You should check first if the directory is ReadOnly or not: 您应首先检查目录是否为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());
    }
}

Thank you, everyone. 谢谢大家。 Here's how I was able to handle it without throwing unnecessary exceptions: 这是我如何能够处理它而不会抛出不必要的例外:

[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