发布时间:2026-09-28 17:00:52 浏览次数:1
Directory.Exists是C#中用于判断指定路径的文件夹是否存在的方法,其返回值为布尔类型,如果存在则返回true,否则返回false。
Directory.Exists方法的使用方法:
bool exists = Directory.Exists(path);其中,path参数为字符串类型的要检查的目录路径。此时exists变量的值为true或false。
以下是Directory.Exists方法的两个示例:
string folderPath = @"C:\Documents\TestFolder";if (Directory.Exists(folderPath)) { Console.WriteLine("文件夹存在");} else { Console.WriteLine("文件夹不存在");}解释:在此示例中,我们用文件夹路径定义了一个字符串变量folderPath,然后使用Directory.Exists方法检查该路径中的文件夹是否存在。如果文件夹存在,则在控制台打印出“文件夹存在”,否则打印“文件夹不存在”。
string[] folderPaths = { @"C:\Documents\TestFolder1", @"C:\Documents\TestFolder2", @"C:\Documents\TestFolder3" };foreach (string folderPath in folderPaths) { if (Directory.Exists(folderPath)) { Console.WriteLine("{0} 文件夹存在", folderPath); } else { Console.WriteLine("{0} 文件夹不存在", folderPath); }}解释:此示例中定义了一个字符串类型的数组folderPaths。然后使用foreach循环遍历这个数组,对于每个folderPath都使用Directory.Exists方法检查对应的文件夹是否存在。最后,根据存在与否,在控制台输出相应的提示信息(例如:"C:\Documents\TestFolder1 文件夹不存在")。