【问题标题】:Do I need to check if directory/file exist or not?我是否需要检查目录/文件是否存在?
【发布时间】:2013-08-12 02:16:40
【问题描述】:

哪一种代码更好?

代码1:

if (!Directory.Exists("DirectoryPathHere"))
    Directory.CreateDirectory("DirectoryPathHere");

代码2:

Directory.CreateDirectory("DirectoryPathHere");

我认为 Code2 因为我看到它没有给出任何错误并且当文件夹已经存在时它不会创建新文件夹,所以我认为检查文件夹是否存在是无用的。对吧?

【问题讨论】:

  • 此类问题的第一站是MSDN。在这种情况下,两秒钟的谷歌搜索 Directory.CreateDirectory 将引导您找到正确的答案。
  • @paddy 我已经知道 MSDN 所说的(我自己弄清楚了),但人们仍在检查文件夹是否存在,所以我想知道为什么?
  • 尽管如此,像这样的防御性编程从来都不是一个坏主意。所以我个人会选择第 1 版。
  • 是 Code2 也是正确的。 CreateDirectory 本身会检查目录是否存在。如果不存在,它将创建。我也同意@SimonWhitehead。
  • @xoemab 有时你想警告你的用户这个文件夹存在,这样他们就不会错误地覆盖他们当前的文件夹,也许这是一个原因,另一个是有些人对错误过于痴迷所以他们会在任何地方进行无根据的检查:)(我也是心理学家)

标签: c# file directory


【解决方案1】:

您不需要检查目录是否已经存在,该方法会为您完成。如果您查看MSDN

创建路径中指定的所有目录,除非它们 已经存在或除非路径的某些部分无效。路径 参数指定目录路径,而不是文件路径。如果 目录已存在,此方法不会创建新目录, 但它会为现有目录返回一个 DirectoryInfo 对象。

【讨论】:

    【解决方案2】:

    我会使用 DirectoryInfo 类,检查它是否存在,如果它确实存在,请检查目录的权限,以防我当前的运行时权限不足以访问内容或更新目录。 您应该将异常处理应用于您使用的任何方法;例如,如果存在具有目录名称的文件怎么办?

    【讨论】:

      【解决方案3】:

      关键是CreateDirectory 方法隐式在尝试创建目录之前检查目录是否存在。

      为了代码的可读性,最好先使用explicit方法Directory.Exists

      我也非常同意@SimonWhitehead 在防御性编程方面的观点。表明你意识到坑掉了......并在你的代码中明确地积极防御它们是一件好事:)

      I think we can all see the fact that the second method does the same, 
      but, is it cheaper in terms of being more readable? No.
      

      任何了解框架的人都可能不同意,我也可以。但是:

      始终像最终维护您的代码的人一样编写代码 知道你住在哪里的暴力精神病患者。

      http://www.codinghorror.com/blog/2008/06/coding-for-violent-psychopaths.html

      编辑 2: 我有一种有趣的感觉,编译器会这样做。汇编程序员可以在生成 IL 之前检测到它。

      【讨论】:

      • 我不明白添加检查是如何防御性编程的,因为它不可能做任何事情。为什么不更加防御并添加更多冗余检查呢? if (!Directory.Exists("DirectoryPathHere") && !Directory.Exists("DirectoryPathHere") && !Directory.Exists("DirectoryPathHere")) {!
      • 我确实同意它更清楚,但我认为评论就足够了。
      • @Blorgbeard 我使用 TFS,很少使用 cmets,因为所有任务都与变更集相关联。显式代码的可读性和维护是我的主要观点。为一个诱人的问题 +1。
      【解决方案4】:

      这是来自http://msdn.microsoft.com/en-us/library/54a0at6s.aspx的简单代码

      using System;
      using System.IO;
      
      class Test 
      {
          public static void Main() 
          {
              // Specify the directory you want to manipulate. 
              string path = @"c:\MyDir";
      
              try 
              {
                  // Determine whether the directory exists. 
                  if (Directory.Exists(path)) 
                  {
                      Console.WriteLine("That path exists already.");
                      return;
                  }
      
                  // Try to create the directory.
                  DirectoryInfo di = Directory.CreateDirectory(path);
                  Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
      
                  // Delete the directory.
                  di.Delete();
                  Console.WriteLine("The directory was deleted successfully.");
              } 
              catch (Exception e) 
              {
                  Console.WriteLine("The process failed: {0}", e.ToString());
              } 
              finally {}
          }
      }
      

      【讨论】:

        【解决方案5】:

        你不需要检查它,但是因为在处理文件和文件夹时会出现很多问题,最好包含try-catch语句以便处理任何潜在的问题:

        try {
           Directory.CreateDirectory("DirectoryPathHere");
        }
        catch (Exception ex)
        {
           MessageBox.Show("Error: "+ex.Message);
        }
        

        如果需要,您也可以添加finally

        【讨论】:

          猜你喜欢
          • 2013-10-01
          • 1970-01-01
          • 2016-09-26
          • 2012-08-18
          • 1970-01-01
          • 2015-11-11
          • 1970-01-01
          • 2022-12-01
          • 2013-08-02
          相关资源
          最近更新 更多