สำหรับการสร้างไดเร็กทอรี เราต้องนำเข้าเนมสเปซ System.IO ใน C# ก่อน เนมสเปซคือไลบรารีที่ให้คุณเข้าถึงเมธอดแบบคงที่สำหรับการสร้าง คัดลอก ย้าย และลบไดเร็กทอรี
ขอแนะนำให้ตรวจสอบเสมอว่าไดเร็กทอรีมีอยู่หรือไม่ก่อนที่จะดำเนินการกับไฟล์ใดๆ ใน 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:

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:
