Làm thể nào để xóa các tập tin và thư mục con trong CSharp? (CSharp How to delete all files and folders in a directory?)


Bài này tôi sẽ hướng dẫn cách delete tất cả các tập tin và thư mục trong một thư mục được chỉ định trong ngôn ngữ lập trình CSharp.





 Mã nguồn - Source Code.

Để thực hiện được bài này chúng ta cần sử dụng kết hợp 4 phương thức Directory.Delete(), File.Delete(), Directory.GetFiles(), Directory.GetDirectories().

Trước tiên bạn cần chuẩn bị một folder có chứa các tập tin và thư mục con để thực hành bài viết này.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HowDeleteFolder
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"D:\Z-Test\VNLIVES_NET";
            delete_01(path);

            System.Console.WriteLine("Delete is succed!");
            System.Console.ReadLine();
        }


        public static void delete_01(string path)
        {
            string[] filePathFiles = Directory.GetFiles(path);
            string[] filePathFolders = Directory.GetDirectories(path);

            foreach (string filePath in filePathFiles)
            {
                File.Delete(filePath);
            }

            foreach (string filePath in filePathFolders)
            {
                Directory.Delete(filePath, true);
            }

        }


    }
}


Kết quả - Result



Như bạn thấy trên hình các tập tin và thư mục trong VNLIVES_NET đã bị xóa tất cả.










No comments:

Post a Comment