C# Directoryinfo class: folder operation

C# Directoryinfo class: folder operation

In the C# language, the Directory class and Directoryinfo class both operate on folders. The DirectoryInfo class can create instances of this class and access class members through the class instances. The DirectoryInfo class provides a construction method, the syntax is as follows.

DirectoryInfo(string path)

For example, create an instance where the path is the test folder in D drive, and the code is as follows.

DirectoryInfo directoryInfo = 
new DirectoryInfo("D:\\test");

The attributes and methods commonly used in the DirectoryInfo class are shown in the following figure.

Insert picture description here
Example 1:

using System;
using System.IO;


namespace MySpcae
{
    
    

    class Program
    {
    
    

        static void Main(string[] args)
        {
    
    
            //创建路径为E盘中的test文件夹
            DirectoryInfo directoryInfo = new DirectoryInfo("E:\\test");
            //创建目录
            directoryInfo.Create();

            //在指定的目录上创建一个或多个子目录
            directoryInfo.CreateSubdirectory("test01");
            directoryInfo.CreateSubdirectory("test02");


            Console.ReadKey();

        }
    }


}


After running, you will get a folder test, and test01 and test02 under it.
Insert picture description here
Example 2:

using System;
using System.IO;
using System.Collections.Generic;


namespace MySpace
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //创建了一个路径为E盘下的test文件夹的实例对象
            DirectoryInfo directoryInfo = new DirectoryInfo("E:\\test");

            //返回当前目录中目录信息的可枚举集合
            IEnumerable<DirectoryInfo> dir = directoryInfo.EnumerateDirectories();
            //遍历集合
            //var在方法范围内声明的变量可以具有隐式“类型”
            foreach (var v in dir)
            {
    
    
                Console.WriteLine(v.Name);
            }
            Console.ReadKey();
        }
    }

}

Results: The
Insert picture description here
EnumerateDirectories method is only used to retrieve folders, not files.

Example 3:
I create a word document in test02 of test01, and then run the following code


using System;
using System.IO;

namespace MySpace
{
    
    


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

            DirectoryInfo directoryInfo = new DirectoryInfo(@"E:\test");
            //指定是否删除子目录和文件,
            //如果 recursive 参数的值为 True,则删除,否则不删除
            directoryInfo.Delete(true);
        }

    }
}

After running, the test folder under the E drive is deleted.
Summary: It
should be noted that if you want to delete a non-empty folder, you must use the Delete (True) method to delete the files in the folder together, otherwise the "folder is not empty" exception will appear.

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/115022035