【.Net实用方法总结】 整理并总结System.IO中DirectoryInfo类及其方法介绍

🐋作者简介:博主是一位.Net开发者,同时也是RPA和低代码平台的践行者。
🐬个人主页:会敲键盘的肘子
🐰系列专栏:.Net实用方法总结
🦀专栏简介:博主针对.Net开发和C站问答过程中遇到的问题进行总结,形成本专栏,希望可以帮助到您解决问题。
🐶座右铭:总有一天你所坚持的会反过来拥抱你。


在这里插入图片描述

🌈写在前面:

本文主要介绍System.IO命名空间的DirectoryInfo 类,介绍其常用的方法和示例说明。


👉本文关键字:System.IO、DirectoryInfo类、文件或目录路径信息、方法示例、C#

1️⃣ System.IO命名空间

.NET中的IO操作命名空间,包含允许读写文件数据流的类型以及提供基本文件和目录支持的类型。

我们在.NET中的IO操作,经常需要调用一下几个类。

  • FileStream类

​ 文件流类,负责大文件的拷贝,读写。

  • Path类

​ Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。

  • File类

    File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。

  • Dirctory类

    目录操作,创建文件、删除目录,获取目录下文件名等等。

2️⃣ DirectoryInfo类

♈ 定义

公开用于创建、移动和枚举目录和子目录实例方法。 此类不能被继承。

public sealed class DirectoryInfo : System.IO.FileSystemInfo
♉ 构造函数
DirectoryInfo(String) 初始化指定路径上的 DirectoryInfo 类的新实例
public DirectoryInfo (string path);

参数

path

string

一个字符串,它指定要在其中创建 DirectoryInfo 的路径。

示例

下面的示例使用此构造函数创建指定的目录和子目录,并演示不能删除包含子目录的目录。

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        // Specify the directories you want to manipulate.
        DirectoryInfo di1 = new DirectoryInfo(@"c:\MyDir");
        DirectoryInfo di2 = new DirectoryInfo(@"c:\MyDir\temp");

        try
        {
            // Create the directories.
            di1.Create();
            di2.Create();

            // This operation will not be allowed because there are subdirectories.
            Console.WriteLine("I am about to attempt to delete {0}.", di1.Name);
            di1.Delete();
            Console.WriteLine("The Delete operation was successful, which was unexpected.");
        }
        catch (Exception)
        {
            Console.WriteLine("The Delete operation failed as expected.");
        }
        finally {}
    }
}

补充

此构造函数不检查目录是否存在。

♊ 字段
FullPath 表示目录或文件的完全限定目录
protected string FullPath;
♋ 属性
CreationTime 获取或设置当前文件或目录的创建时间
public DateTime CreationTime { get; set; }
Exists 获取指示目录是否存在的值
public abstract bool Exists { get; }
Extension 获取文件名的扩展名部分,包括前导点即使它是整个文件名,或者不存在扩展名的空字符串
public string Extension { get; }
FullName 获取目录或文件的完整目录
public virtual string FullName { get; }
Name 获取此 DirectoryInfo 实例的名称
public override string Name { get; }

Name此属性仅返回目录的名称,例如"Bin"。 若要获取完整路径,例如"c:\public\Bin",请使用 FullName 属性。

Parent 获取指定的子目录的父目录
public System.IO.DirectoryInfo? Parent { get; }

示例

using System;
using System.IO;

public class MoveToTest
{
    public static void Main()
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (di.Exists == false)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Get a reference to the parent directory of the subdirectory you just made.
        DirectoryInfo parentDir = dis.Parent;
        Console.WriteLine("The parent directory of '{0}' is '{1}'", dis.Name, parentDir.Name);

        // Delete the parent directory.
        di.Delete(true);
    }
}
Root 获取目录的根部分
public System.IO.DirectoryInfo Root { get; }
♌ 常用方法
Create() 创建目录
public void Create ();

示例

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        // Specify the directories you want to manipulate.
        DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");

        try
        {
            // Determine whether the directory exists.
            if (di.Exists)
            {
                // Indicate that it already exists.
                Console.WriteLine("That path exists already.");
                return;
            }

            // Try to create the directory.
            di.Create();
            Console.WriteLine("The directory was created successfully.");

            // Delete the directory.
            di.Delete();
            Console.WriteLine("The directory was deleted successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
        finally {}
    }
}

补充

如果该目录已存在,则此方法不执行任何操作。

CreateSubdirectory(String) 创建目录
public System.IO.DirectoryInfo CreateSubdirectory (string path);

参数

path

string

指定的路径。

返回

DirectoryInfo

path 中指定的最后一个目录。

示例

下面的示例演示如何创建子目录。 在此示例中,创建的目录在创建后将被删除。 因此,若要测试此示例,请在代码中注释掉删除行。

using System;
using System.IO;

public class CreateSubTest
{
    public static void Main()
    {
        // Create a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (di.Exists == false)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Process that directory as required.
        // ...

        // Delete the subdirectory.
        dis.Delete(true);

        // Delete the directory.
        di.Delete(true);
    }
}
Delete(Boolean) 从指定路径删除空目录
public void Delete (bool recursive);

参数

recursive

bool

如果要删除此目录,则为 true;否则为 false

示例

using System;
using System.IO;

public class DeleteTest
{
    public static void Main()
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (di.Exists == false)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Process that directory as required.
        // ...

        // Delete the subdirectory. The true indicates that if subdirectories
        // or files are in this directory, they are to be deleted as well.
        dis.Delete(true);

        // Delete the directory.
        di.Delete(true);
    }
}
EnumerateFiles() 返回当前目录中的文件信息的可枚举集合
public System.Collections.Generic.IEnumerable<System.IO.FileInfo> EnumerateFiles ();

返回

IEnumerable

一个可枚举集合,它包含目录中 path 指定的文件的完整名称(包括路径)。

示例

// Create a DirectoryInfo of the directory of the files to enumerate.
DirectoryInfo DirInfo = new DirectoryInfo(@"\\archives1\library\");

DateTime StartOf2009 = new DateTime(2009, 01, 01);

// LINQ query for all files created before 2009.
var files = from f in DirInfo.EnumerateFiles()
           where f.CreationTimeUtc < StartOf2009
           select f;

// Show results.
foreach (var f in files)
{
    Console.WriteLine("{0}", f.Name);
}

如果只需要文件的名称,请使用静态 Directory 类以提高性能。

EnumerateFiles GetFiles 方法不同,如下所示:

  • 使用 时 EnumerateFiles ,可以在返回整个集合 FileInfo 之前开始枚举 对象的集合。
  • 使用 时 GetFiles ,必须等待返回整个 对象数组 FileInfo ,然后才能访问数组。

因此,当你使用许多文件和目录时, EnumerateFiles 可能更高效。

EnumerateFiles(String) 返回与搜索模式匹配的文件信息的可枚举集合
public System.Collections.Generic.IEnumerable<System.IO.FileInfo> EnumerateFiles (string searchPattern);

参数

searchPattern

string

要与 path 中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和通配符(* 和 ?)的组合,但不支持正则表达式。例如,"*.txt"

返回

IEnumerable

一个可枚举集合,它包含目录中 path 指定的文件的完整名称(包括路径)。

EnumerateFiles(String, SearchOption) 返回与指定的搜索模式和枚举选项匹配的文件信息的可枚举集合录
public System.Collections.Generic.IEnumerable<System.IO.FileInfo> EnumerateFiles (string searchPattern, System.IO.SearchOption searchOption);

参数

searchPattern

string

要与 path 中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和通配符(* 和 ?)的组合,但不支持正则表达式。例如,"*.txt"

searchOption

SearchOption

指定搜索操作是应仅包含当前目录还是应包含所有子目录的枚举值之一。 默认值是 TopDirectoryOnly

返回

IEnumerable

一个可枚举集合,它包含目录中 path 指定的文件的完整名称(包括路径)。

示例

下面的示例演示如何使用不同的搜索选项枚举目录中的文件。 该示例假设有一个目录,其中包含名为 log1.txt、log2.txt、test1.txt、test2.txt、test3.txt 的文件,以及一个包含名为 SubFile.txt 的文件的子目录。

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo(@"C:\ExampleDir");
            Console.WriteLine("No search pattern returns:");
            foreach (var fi in di.EnumerateFiles())
            {
                Console.WriteLine(fi.Name);
            }

            Console.WriteLine();

            Console.WriteLine("Search pattern *2* returns:");
            foreach (var fi in di.EnumerateFiles("*2*"))
            {
                Console.WriteLine(fi.Name);
            }

            Console.WriteLine();

            Console.WriteLine("Search pattern test?.txt returns:");
            foreach (var fi in di.EnumerateFiles("test?.txt"))
            {
                Console.WriteLine(fi.Name);
            }

            Console.WriteLine();

            Console.WriteLine("Search pattern AllDirectories returns:");
            foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
            {
                Console.WriteLine(fi.Name);
            }
        }
    }
}
/*
This code produces output similar to the following:

No search pattern returns:
log1.txt
log2.txt
test1.txt
test2.txt
test3.txt

Search pattern *2* returns:
log2.txt
test2.txt

Search pattern test?.txt returns:
test1.txt
test2.txt
test3.txt

Search pattern AllDirectories returns:
log1.txt
log2.txt
test1.txt
test2.txt
test3.txt
SubFile.txt
Press any key to continue . . .

*/
MoveTo(String) 将 DirectoryInfo 实例及其内容移动到新路径
public void MoveTo (string destDirName);

参数

destDirName

string

新位置 sourceDirName 的路径或其内容。 如果 sourceDirName 是文件,那么 destDirName 也必须是文件名。

示例

以下示例演示如何将目录及其所有文件移动到新目录。 移动原始目录后不再存在。

using System;
using System.IO;

public class MoveToTest
{
    public static void Main()
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (di.Exists == false)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Move the main directory. Note that the contents move with the directory.
        if (Directory.Exists("NewTempDir") == false)
            di.MoveTo("NewTempDir");

        try
        {
            // Attempt to delete the subdirectory. Note that because it has been
            // moved, an exception is thrown.
            dis.Delete(true);
        }
        catch (Exception)
        {
            // Handle this exception in some way, such as with the following code:
            // Console.WriteLine("That directory does not exist.");
        }

        // Point the DirectoryInfo reference to the new directory.
        //di = new DirectoryInfo("NewTempDir");

        // Delete the directory.
        //di.Delete(true);
    }
}
♍ 注解

如果要多次重用某个对象,请考虑使用的实例方法(而不是 DirectoryInfo 类的相应静态方法 Directory ),因为安全检查并不总是必需的。

♎ 更多方法

更多方法请查阅官方文档DirectoryInfo 类


⭐写在结尾:

文章中出现的任何错误请大家批评指出,一定及时修改。

希望写在这里的小伙伴能给个三连支持

  • 14
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会敲键盘的肘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值