首頁  >  文章  >  後端開發  >  C#中如果資料夾不存在如何建立?

C#中如果資料夾不存在如何建立?

WBOY
WBOY轉載
2023-09-11 11:57:091838瀏覽

為了建立目錄,我們必須先在C#中匯入System.IO命名空間。命名空間是一個庫,可讓您存取用於建立、複製、移動和刪除目錄的靜態方法。

總是建議在 C# 中執行任何檔案操作之前檢查目錄是否存在,因為編譯器如果資料夾不存在,將會拋出例外。

範例

using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string folderName = @"D:\Demo Folder";
         // If directory does not exist, create it
         if (!Directory.Exists(folderName)) {
            Directory.CreateDirectory(folderName);
         }
         Console.ReadLine();
      }
   }
}

上面的程式碼會在D:目錄下建立一個Demo資料夾。

C#中如果資料夾不存在如何建立?

Directory.CreateDirectory 也可用於建立子資料夾。

範例

using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string folderName = @"D:\Demo Folder\Sub Folder";
         // If directory does not exist, create it
         if (!Directory.Exists(folderName)) {
            Directory.CreateDirectory(folderName);
         }
         Console.ReadLine();
      }
   }
}

上述程式碼將在 D: 目錄中建立一個帶有子資料夾的演示資料夾

C#中如果資料夾不存在如何建立?

以上是C#中如果資料夾不存在如何建立?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除