📜  C# 程序创建目录(1)

📅  最后修改于: 2023-12-03 15:13:52.293000             🧑  作者: Mango

C# 程序创建目录

在开发过程中,有时候需要在程序中创建目录来存储文件或者其他数据。本文将介绍在C#中如何创建目录。

使用 System.IO.Directory 类创建目录

C#中可以使用 System.IO.Directory 类中的 CreateDirectory() 方法创建目录。以下是该方法的语法:

public static void CreateDirectory(string path);

其中,path 参数指定要创建的目录的路径。如果在路径中指定的目录不存在,则会自动创建它。

以下是一个使用 CreateDirectory() 方法创建目录的示例代码:

using System.IO;

class Program {
  static void Main(string[] args) {
    string path = @"c:\temp\MyTestDirectory";

    // Create the directory if it does not exist
    if (Directory.Exists(path)) {
      Console.WriteLine("That path exists already.");
      return;
    }

    Directory.CreateDirectory(path);
    Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
  }
}

在上面的示例代码中,如果指定的目录路径已经存在,则不会重新创建该目录。程序会直接返回。

使用 System.IO.Path 类创建目录

C#中也可以使用 System.IO.Path 类中的 Combine() 方法创建目录。以下是该方法的语法:

public static string Combine(string path1, string path2);

其中,path1 是目录的父路径,path2 是要创建的目录名称。

以下是一个使用 Combine() 方法创建目录的示例代码:

using System.IO;

class Program {
  static void Main(string[] args) {
    string path1 = @"c:\temp";
    string path2 = "MyTestDirectory";

    // Combine the paths and create the directory
    string fullPath = Path.Combine(path1, path2);
    Directory.CreateDirectory(fullPath);
    Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(fullPath));
  }
}

在这个示例代码中,使用 Path.Combine() 方法将父路径和要创建的目录名称合并为完整的目录路径。

总结

本文介绍了在C#中使用 System.IO.Directory 类和 System.IO.Path 类创建目录的方法。开发者可以根据自己的需要来选择使用哪种方法。无论使用哪种方法,都需要确保要创建的目录不存在,否则可能会导致程序异常。