【.NET Core】深入理解IO之文件和目录

一、概述

文件和流I/O(输入/输出)是指在存储媒介中传入或传出数据。在.NET中,System.IO命名空间包含允许以异步方式和同步方式对数据流和文件进行读取和写入操作的类型。这些命名空间还包含对文件执行压缩和解压的类型,以及通过管道和串行端口启用通信的类型。

文件是一个由字节组成的有序的命名集合,它具有永久存储。你将处理目录路径、磁盘存储、文件和目录名称。 相反,流是一个字节序列,可用于对后备存储进行读取和写入操作,后备存储可以是多个存储媒介之一(例如,磁盘或内存)。

二、Directory详解

Directory用于通过目录和子目录进行创建、移动和枚举的静态方法。 此类不能被继承。Directory类中的静态方法对所有方法执行安全检查。如果要多次重用对象,使用DirectoryInfo,因为安全检查并非始终是必需的。

如果只执行一个与目录相关的操作,则使用静态Directory方法而不是相对的DirectoryInfo实例方法可能更有效。

2.1 Directory.CreateDirectory 方法

在指定路径中创建所有目录。

  • 重载方法说明
  • 注解

将创建中path指定的任何目录和所有目录,除非它们已存在,或者除非的path某个部分无效。如果目录已存在,此方法不会创建新目录,但会返回DirectoryInfo目录的对象。

参数path指定目录路径,而不是文件路径。path不支持创建仅包含冒号字符(:)的目录,这将导致NotSupportedException引用。在Unix系统上,使用/(正斜杠作为路径分隔符)

  • 应用示例
 public static void Main()
    {
        string path = @"D:\Goyeer\2024\02\22\";
        try
        {
            if (Directory.Exists(path))
            {
                Console.WriteLine("That path exists already.");
                return;
            }
            DirectoryInfo di = Directory.CreateDirectory(path);
            Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
            di.Delete();
            Console.WriteLine("The directory was deleted successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
        finally {}
    }

2.2 Directory.Delete方法

从指定路径删除空目录。

  • 重载方法说明
  • 注解

此方法的行为与相同,Delete(String,Boolean)。参数path可以指定相对或绝对路径信息。相对路径信息解释为相对于当前工作目录。删除目录之前path将从参数末尾删除尾部跟随空格。

数的 path 区分大小写对应于运行代码的文件系统的区分大小写。

在某些情况下,如果在 文件资源管理器 中打开了指定的目录,则 Delete方法可能无法删除它。

  • 应用示例
string path = @"D:\Goyeer\2024\02\22\";
Directory.Delete(topPath, true);

2.3 Directory.GetCreationTime方法

获取目录创建的日期和时间

  • 注解

此方法可能返回不准确的值,因为它使用本机函数,其值可能不会由操作系统持续更新。

如果参数中描述path目录不存在,此方法返回1601年1月1日

DateTime dt = Directory.GetCreationTime(Environment.CurrentDirectory);

2.4 Directory.GetCurrentDirectory方法

GetCurrentDirectory只是返回操作系统的当前目录,并不一定返回你的应用程序的目录。比如你在应用程序中调用了打开文件对话框,你选择了一个文件,那么,这个文件所在的目录就成了操作系统的当前目录了。因此,千万不要用这个函数作为获取应用程序目录的手段。

获取当前应用程序主目录的方法是GetModuleFileName,先获取应用程序文件路径,然后截取调应用程序文件名称就是应用程序主目录了。

  • 示例
string path = Directory.GetCurrentDirectory();
string targetPath = @"d:\temp";
Console.WriteLine("The current directory is {0}", path);
if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(target);
}

2.5 Directory.GetDirectories 方法

返回满足指定条件的子目录的名称

  • 重载
  • 注解

参数path可以指定相对或绝对路径信息,并且不区分大小写。相对路径信息解释为相对于当前工作目录。

  • 示例
string[] dirs = Directory.GetDirectories(@"c:\", "p*", SearchOption.TopDirectoryOnly);
Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length);
foreach (string dir in dirs)
{
   Console.WriteLine(dir);
}

2.6 Directory.GetDirectoryRoot方法

返回指定路径的卷信息、根信息或两者同时返回

  • 注解

此方法获取,返回GetFullPathpath的完全限定路径名,并返回根目录信息。指定路径不需要存在。允许path参数指定相对路径信息或绝对路径信息。相对路径信息被解释为相对于当前工作目录。

  • 示例
public static void DirectoryRootDemo()
{
   string dir = @"C:\test";		
   try
   {
       Directory.SetCurrentDirectory(dir);
   }
   catch (DirectoryNotFoundException e)
   {
       Console.WriteLine("The specified directory does not exist. {0}", e);
   }
   Console.WriteLine("Root directory: {0}", Directory.GetDirectoryRoot(dir));
   Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory());
}

2.7 Directory.GetFiles 方法

返回满足指定条件的文件的名称。

  • 重载
  • 示例
public  void ProcessDirectory(string targetDirectory)
{
     string [] fileEntries = Directory.GetFiles(targetDirectory);
     foreach(string fileName in fileEntries)
     {
          Console.WriteLine($"Current directory: {fileName}",
     }      
}

2.8 Directory.Move(String, String) 方法

将文件或目录及其内容移到新位置。此方法使用 指定 destDirName 的名称创建一个新目录,并将 的内容 sourceDirName(包括文件和目录)移动到新创建的目标目录。 然后,它会删除该 sourceDirName 目录

public void MoveDemo(string[] args)
{
      string sourceDirectory = @"d:\source";
      string destinationDirectory = @"d:\destination";
      try
      {
          Directory.Move(sourceDirectory, destinationDirectory);
      }
      catch (Exception e)
      {
           Console.WriteLine(e.Message);
       }
 }
03-02 19:13