C# Directory.Exists(string path):判断指定路径的目录是否存在

  • Post category:C#

Directory.Exists(string path) 方法是 C# 中 System.IO 命名空间中的一个静态方法,用于判断指定目录是否存在。该方法有一个参数 path,用于指定需要检查的目录的路径字符串。

使用该方法可以避免程序出错的风险,防止程序在尝试读取或写入不存在的目录时发生异常。

下面是该方法的完整使用攻略:

  1. 判断目录是否存在

使用示例:

string path = @"D:\Temp\test";
if (Directory.Exists(path))
{
    Console.WriteLine("目录已经存在.");
}
else
{
    Console.WriteLine("目录不存在,正在创建中...");
    Directory.CreateDirectory(path);
}

该示例中,首先定义了需要检查的目录路径 path,其后通过 Directory.Exists 方法判断该目录是否存在。如果返回值为 true,表示目录已经存在,程序将输出”目录已经存在”,否则说明目录不存在,调用 Directory.CreateDirectory 方法创建该目录。

  1. 列出指定目录下的所有子目录

使用示例:

string path = @"D:\Temp";
if (Directory.Exists(path))
{
    var subDirectories = Directory.GetDirectories(path);
    foreach (var subDirectory in subDirectories)
    {
        Console.WriteLine(subDirectory);
    }
}

该示例中,首先定义了需要列出子目录的目录路径 path,通过 Directory.Exists 方法判断该目录是否存在。如果返回值为 true,表示目录已经存在,接下来通过 Directory.GetDirectories 方法获取该目录下所有子目录的路径。遍历所有子目录并输出对应的路径。

需要注意的是,当 GetDirectories 方法调用时发生异常时,将会抛出对应的异常。因此,在使用该方法时最好将其放置于 try…catch…代码块中。

总结:

Directory.Exists 方法可以用于判断指定的目录是否存在,从而避免因操作不存在的目录而引起的错误。当需要列出指定目录下的所有子目录时,可使用 Directory.GetDirectories 方法。