Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tạo thư mục nếu chưa tồn tại trong C#

Để tạo directory, phải import namespace System.IO. Namespace này cung cấp static methods tạo, copy, move, delete directories.

Luôn khuyến nghị kiểm tra Directory tồn tại trước khi thao tác file trong C# vì compiler ném exception nếu folder không tồn tại.

Ví dụ

using System;
using System.IO;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderName = @"D:\Demo Folder";
            // Nếu directory không tồn tại, tạo mới
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }
            Console.ReadLine();
        }
    }
}

Code trên tạo folder Demo Folder ở ổ D:.

Tạo thư mục nếu chưa tồn tại trong C#

Directory.CreateDirectory cũng tạo subfolders.

Ví dụ tạo subfolder

using System;
using System.IO;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderName = @"D:\Demo Folder\Sub Folder";
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }
            Console.ReadLine();
        }
    }
}

Tạo Demo Folder với Sub Folder ở ổ D:.

Tạo thư mục nếu chưa tồn tại trong C#