C#(099):文件读写(一)利用File静态类 System.IO.FileInfo、DirectoryInfo、DriveInfo(C# (099): file reading and writing (I) using file static class system IO. FileInfo、DirectoryInfo、DriveInfo)

提供用于创建、复制、删除、移动和打开单一文件的静态方法,并协助创建

[FileStream](https://docs.microsoft.com/zh-
cn/dotnet/api/system.io.filestream?view=netframework-4.8) 对象。

一、读文件:

1、返回字符串:

    string readText = File.ReadAllText(@"c:\temp\MyTest.txt");

2、返回字符串数组:

    string[] readText = File.ReadAllLines(@"c:\temp\MyTest.txt", Encoding.UTF8);

3、返回字节数组:

    byte[] buffer = File.ReadAllBytes(@"c:\temp\MyTest.txt");
    string str = Encoding.Default.GetString(buffer, 0, buffer.Length);

4、返回StreamReader

打开现有的UTF-8文本以进行读取

    using (StreamReader sr = File.OpenText(@"c:\temp\MyTest.txt"))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }

二、写文件

创建一个新文件向其中写入内容,文件已存在则覆盖。

1、写入字符串:

    string createText = "Hello and Welcome" + Environment.NewLine;
    File.WriteAllText(path, createText);//File.WriteAllText(),File.AppendAllText()

2、写入字符串数组:

    string[] createText = { "Hello", "And", "Welcome" };
    File.WriteAllLines(path, createText);

3、写入字节数组:

    string str = "哈哈哈哈哈哈";
    byte[] buffer = Encoding.Default.GetBytes(str);
    File.WriteAllBytes(path,buffer);

4、返回StreamWriter

创建或打开现有的UTF-8文本,以进行写入或追加

    using (StreamWriter sw = File.CreateText(path)) //StreamWriter:File.CreateText()、File.AppendText()
    {
        sw.WriteLine("Hello");
        sw.WriteLine("And");
        sw.WriteLine("Welcome");
    }

三、返回FileStream的操作

File.Open():默认为不共享、具有读/写访问权限

    using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
    {
        byte[] b = new byte[1024];
        UTF8Encoding temp = new UTF8Encoding(true);
    
        while (fs.Read(b, 0, b.Length) > 0)
        {
            Console.WriteLine(temp.GetString(b));
        }
    }

File.OpenRead():读访问权限

File.OpenWrite:写访问权限

    using (FileStream fs = File.OpenWrite(path))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");
    
        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }

File.Create():

    using (FileStream fs = File.Create(path))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }

四、File类的常用操作:

  • 文件删除方法: File.Delete()
  • 文件复制方法: File.Copy()
  • 文件移动方法: File.Move()
  • 设置文件属性方法: File.Set/Get()*
  • 判断文件是否存在的方法: File.Exist()

五、Directory类的常用操作:

    //删除此目录
    Directory.Delete(@"C:\新建文件夹")
    
    //删除此目录,true表示要是此目录有子目录也删除,否则就抛出异常
    Directory.Delete(@"C:\新建文件夹", false);
    
    //此目录是否存在
    bool b = Directory.Exists(@"C:\新建文件夹");
    
    //根据路径返回此目录下的子目录
    string[] dirs1 = Directory.GetDirectories(@"C:\新建文件夹");
    
    //第二个参数表示:搜索的范围,就是搜索的文件夹包含“基础”关键字
    string[] dirs2 = Directory.GetDirectories(@"C:\新建文件夹", "基础");
    
    //搜索目录下的所有文件
    string[] files = Directory.GetFiles(@"C:\新建文件夹");
    
    //第三个参数表示:指定搜索操作应包括所有子目录还是仅包括当前目录。
    string[] files1 = Directory.GetFiles(@"C:\新建文件夹", "2.txt", SearchOption.AllDirectories);
    
    //(获取指定目录下的所有目录时返回一个DirectoryInfo数组。)
    DirectoryInfo dirs = Directory.GetParent(@"C:\新建文件夹");
    
    //移动、剪切。只能在同一个磁盘中。目录没有Copy方法。可以使用Move()方法实现重命名。
    Directory.Move(@"F:\测试\33", @"F:\测试\32\33");

六、FileSystemInfo

派生类:

  • DirectoryInfo
  • FileInfo

1、FileInfo类

    //实例化FileInfo进行操作
    FileInfo myfile = new FileInfo(path); //声明一个对象对某一个文件进行操作
    myfile.CopyTo(destpath);  //对文件进行复制操作,复制路径为destpath
    myfile.MoveTo(destpath);  //进行移动操作
    myfile.Delete();          //进行删除操作
    
    //获得某一文件或文件夹的详细信息(创建日期,最后一次修改日期等等)
    FileInfo myfile = new FileInfo(path); //声明一个对象对某一个文件进行操作
    DateTime dt = myfile.CreationTime;  //获取或设置文件/文件夹的创建日期
    string filepath = myfile.DirectoryName; //仅能用于FileInfo,获得完整的路径名,路径+文件名
    bool file = myfile.Exists;              //此属性的值表示文件或文件夹是否存在,存在会返回True
    string fullname = myfile.FullName;     //获取文件或文件夹的完整路径名
    DateTime lastTime = myfile.LastAccessTime; //获取或设置最后一次访问文件或文件夹的时间
    DateTime lastWrite = myfile.LastWriteTime; //获取或设置最后一次修改文件夹或文件夹的时间
    string name = myfile.Name;                 //获取文件名,不能修改哦
    long length = myfile.Length;                  //返回文件的字节大小
    //CreationTime,LastAccessTime,LastWriteTime都是可以被修改的。

2、DirectoryInfo类

    DirectoryInfo dir = new DirectoryInfo(@"d:\C#程序设计");
    if (!dir.Exists)
    {
        dir.Create();
    }
    else
    {
        Console.WriteLine("该目录已经存在");
    }

七、DriveInfo类

在Windows操作系统中,存储介质统称为驱动器,硬盘由于可以划分为多个区域,每一个区域称为一个驱动器。

DriveInfo类的常用字段成员有

  • DriveFormat(文件系统格式,如NTFS或FAT32)、
  • DriveType(驱动器类型)、
  • Name(驱动器名)、
  • TotalSize(总空间)、
  • TotalFreeSpace(获得驱动器可用空间)。

常用的方法成员有GetDrives(获得可用驱动器列表)。

DriveType枚举型的枚举值有CDRom(光驱)、Fixed(硬盘)、Network(网络驱动器)和Removeable(软盘或U盘)等。

例如,以下代码可以输出每一个硬盘驱动器的剩余空间信息。

    DriveInfo[] drivers = DriveInfo.GetDrives();
    foreach (DriveInfo driver in drivers)
    {
        if (driver.DriveType == DriveType.Fixed && driver.DriveFormat == "NTFS")
        {
            Console.WriteLine("在{0}驱动器上还有{1}字节的剩余空间。", driver.Name, driver.AvailableFreeSpace);
        }
    }
————————

Provides static methods for creating, copying, deleting, moving, and opening a single file, and assists in creation

[FileStream](https://docs.microsoft.com/zh-
cn/dotnet/api/system.io.filestream?view=netframework-4.8) 对象。

1、 Read file:

< strong > 1. Return string: < / strong >

    string readText = File.ReadAllText(@"c:\temp\MyTest.txt");

< strong > 2. Return string array: < / strong >

    string[] readText = File.ReadAllLines(@"c:\temp\MyTest.txt", Encoding.UTF8);

< strong > 3. Return byte array: < / strong >

    byte[] buffer = File.ReadAllBytes(@"c:\temp\MyTest.txt");
    string str = Encoding.Default.GetString(buffer, 0, buffer.Length);

4、返回StreamReader

Open existing UTF-8 text for reading

    using (StreamReader sr = File.OpenText(@"c:\temp\MyTest.txt"))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }

2、 Write file

Create a new file and write to it. If the file already exists, overwrite it.

< strong > 1. Write string: < / strong >

    string createText = "Hello and Welcome" + Environment.NewLine;
    File.WriteAllText(path, createText);//File.WriteAllText(),File.AppendAllText()

< strong > 2. Write string array: < / strong >

    string[] createText = { "Hello", "And", "Welcome" };
    File.WriteAllLines(path, createText);

< strong > 3. Write byte array: < / strong >

    string str = "哈哈哈哈哈哈";
    byte[] buffer = Encoding.Default.GetBytes(str);
    File.WriteAllBytes(path,buffer);

4、返回StreamWriter

Create or open existing UTF-8 text for writing or appending

    using (StreamWriter sw = File.CreateText(path)) //StreamWriter:File.CreateText()、File.AppendText()
    {
        sw.WriteLine("Hello");
        sw.WriteLine("And");
        sw.WriteLine("Welcome");
    }

三、返回FileStream的操作

File. Open (): the default is not shared and has read / write access < / strong >

    using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
    {
        byte[] b = new byte[1024];
        UTF8Encoding temp = new UTF8Encoding(true);
    
        while (fs.Read(b, 0, b.Length) > 0)
        {
            Console.WriteLine(temp.GetString(b));
        }
    }

File. Openread(): read access rights < / strong >

slightly

File.OpenWrite:写访问权限

    using (FileStream fs = File.OpenWrite(path))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");
    
        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }

File.Create():

    using (FileStream fs = File.Create(path))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }

4、 Common operations of file class:

  • File deletion method: file Delete()
  • File copy method: file Copy()
  • File move method: file Move()
  • Method for setting file attributes: file Set/Get()*
  • Method to judge whether a file exists: file Exist()

5、 Common operations of directory class:

    //删除此目录
    Directory.Delete(@"C:\新建文件夹")
    
    //删除此目录,true表示要是此目录有子目录也删除,否则就抛出异常
    Directory.Delete(@"C:\新建文件夹", false);
    
    //此目录是否存在
    bool b = Directory.Exists(@"C:\新建文件夹");
    
    //根据路径返回此目录下的子目录
    string[] dirs1 = Directory.GetDirectories(@"C:\新建文件夹");
    
    //第二个参数表示:搜索的范围,就是搜索的文件夹包含“基础”关键字
    string[] dirs2 = Directory.GetDirectories(@"C:\新建文件夹", "基础");
    
    //搜索目录下的所有文件
    string[] files = Directory.GetFiles(@"C:\新建文件夹");
    
    //第三个参数表示:指定搜索操作应包括所有子目录还是仅包括当前目录。
    string[] files1 = Directory.GetFiles(@"C:\新建文件夹", "2.txt", SearchOption.AllDirectories);
    
    //(获取指定目录下的所有目录时返回一个DirectoryInfo数组。)
    DirectoryInfo dirs = Directory.GetParent(@"C:\新建文件夹");
    
    //移动、剪切。只能在同一个磁盘中。目录没有Copy方法。可以使用Move()方法实现重命名。
    Directory.Move(@"F:\测试\33", @"F:\测试\32\33");

六、FileSystemInfo

Derived classes:

  • DirectoryInfo
  • FileInfo

1、FileInfo类

    //实例化FileInfo进行操作
    FileInfo myfile = new FileInfo(path); //声明一个对象对某一个文件进行操作
    myfile.CopyTo(destpath);  //对文件进行复制操作,复制路径为destpath
    myfile.MoveTo(destpath);  //进行移动操作
    myfile.Delete();          //进行删除操作
    
    //获得某一文件或文件夹的详细信息(创建日期,最后一次修改日期等等)
    FileInfo myfile = new FileInfo(path); //声明一个对象对某一个文件进行操作
    DateTime dt = myfile.CreationTime;  //获取或设置文件/文件夹的创建日期
    string filepath = myfile.DirectoryName; //仅能用于FileInfo,获得完整的路径名,路径+文件名
    bool file = myfile.Exists;              //此属性的值表示文件或文件夹是否存在,存在会返回True
    string fullname = myfile.FullName;     //获取文件或文件夹的完整路径名
    DateTime lastTime = myfile.LastAccessTime; //获取或设置最后一次访问文件或文件夹的时间
    DateTime lastWrite = myfile.LastWriteTime; //获取或设置最后一次修改文件夹或文件夹的时间
    string name = myfile.Name;                 //获取文件名,不能修改哦
    long length = myfile.Length;                  //返回文件的字节大小
    //CreationTime,LastAccessTime,LastWriteTime都是可以被修改的。

2、DirectoryInfo类

    DirectoryInfo dir = new DirectoryInfo(@"d:\C#程序设计");
    if (!dir.Exists)
    {
        dir.Create();
    }
    else
    {
        Console.WriteLine("该目录已经存在");
    }

七、DriveInfo类

In the windows operating system, storage media are collectively referred to as drives. Since hard disks can be divided into multiple regions, each region is called a drive.

The common field members of driveinfo class are

  • DriveFormat(文件系统格式,如NTFS或FAT32)、
  • DriveType(驱动器类型)、
  • Name
  • TotalSize(总空间)、
  • TotalFreeSpace(获得驱动器可用空间)。

A common method member is getdrives (get a list of available drives).

The enumeration values of drivetype enumeration type include CDROM (optical drive), fixed (hard disk), network (network drive) and removable (floppy disk or U disk), etc.

For example, the following code can output the remaining space information of each hard disk drive.

    DriveInfo[] drivers = DriveInfo.GetDrives();
    foreach (DriveInfo driver in drivers)
    {
        if (driver.DriveType == DriveType.Fixed && driver.DriveFormat == "NTFS")
        {
            Console.WriteLine("在{0}驱动器上还有{1}字节的剩余空间。", driver.Name, driver.AvailableFreeSpace);
        }
    }