如何在 C# 中建立資料夾
Minahil Noor
2024年2月16日

在本文中,我們將介紹在指定目錄中建立新資料夾的方法。
- 使用
CreateDirectory()
方法
使用 CreateDirectory()
方法在 C# 中建立一個資料夾
我們將使用系統定義的方法 CreateDirectory()
在指定的目錄中建立一個新的資料夾。如果資料夾已經存在,那麼它就不會採取任何操作。使用該函式的正確語法如下。
System.IO.Directory.CreateDirectory(string path);
內建方法 CreateDirectory()
只有一個引數。其引數的詳細資訊如下。
引數 | 說明 | |
---|---|---|
path |
強制 | 它是包含路徑資訊的字串,我們要在其中建立一個新的資料夾 |
這個方法返回一個 DirectoryInfo
物件,顯示指定路徑的目錄。
下面的程式顯示了我們如何使用 CreateDirectory()
方法來建立一個新的資料夾。
using System;
using System.IO;
class CreateFolder {
static void Main() {
string folderPath = @"D:\MyFolder";
if (!Directory.Exists(folderPath)) {
Directory.CreateDirectory(folderPath);
Console.WriteLine(folderPath);
}
}
}
我們已經在本地磁碟 D 中建立了一個名為 MyFolder
的資料夾。我們已經傳遞了資料夾的路徑。如果資料夾不存在,該方法將建立該資料夾。
輸出:
D:\MyFolder