我需要检查目录/文件是否存在吗

本文关键字:文件 是否 存在 检查 | 更新日期: 2023-09-27 18:27:27

哪一个代码更好?

代码1:

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

代码2:

Directory.CreateDirectory("DirectoryPathHere");

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

我需要检查目录/文件是否存在吗

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

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

我会使用DirectoryInfo类,检查它是否存在,如果它确实存在,也可能检查目录上的权限,以防我当前的运行时权限不足以访问内容或更新目录。无论使用哪种方法,都应该应用异常处理;例如,如果存在一个具有目录名的文件,该怎么办?

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

为了代码的可读性,最好先使用显式方法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之前检测到它。

下面是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 {}
    }
}

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

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

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