0

I have the following C# code that creates a folder:

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..

Any idea how to prevent that apart from catching such exception, which I prefer to avoid?

4

3 回答 3

1

您应该首先检查目录是否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());
    }
}
于 2013-08-04T21:29:09.483 回答
1

根据文档

如果您没有对该目录的最低只读权限,则 Exists 方法将返回 false。

因此,您看到的行为是预期的。这是一个合法的异常,即使您确实检查了权限也可能发生,因此最好的办法是简单地处理异常。

于 2013-08-04T21:15:19.663 回答
0

谢谢大家。以下是我如何在不引发不必要异常的情况下处理它:

[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);
        }
    }
}
于 2013-08-04T21:39:22.197 回答