【问题标题】:Issues checking if folder exists检查文件夹是否存在的问题
【发布时间】:2013-08-04 21:11:00
【问题描述】:

我有以下创建文件夹的 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.

除了捕获这种我更愿意避免的异常之外,知道如何防止这种情况发生吗?

【问题讨论】:

  • 存在和写权限是两个不同的东西。
  • 您可以单独使用Directory.CreateDirectory 来检查字典是否存在。然后你也避免了竞争条件。
  • UserName 您登录时使用的用户名或其他用户帐户,您和管理员以及您的应用程序是否以管理员权限运行?
  • @TimSchmelter: Directory.CreateDirectory 将引发 access denied 异常,这就是我试图避免的。
  • @c00000fd - 无论如何你都可能得到这个异常。即使您确实事先检查了权限,它仍然可能在您检查和尝试访问它之间发生变化。如果可能,您需要处理此异常。

标签: c# .net directory


【解决方案1】:

According to the docs:

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

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

【讨论】:

    【解决方案2】:

    您应该首先检查目录是否为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());
        }
    }
    

    【讨论】:

      【解决方案3】:

      谢谢大家。以下是我能够在不引发不必要异常的情况下处理它的方法:

      [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);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        • 2013-03-12
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        相关资源
        最近更新 更多