【小沐学C#】C#文件读写方式汇总

1、简介

文件读写在计算机编程中起着至关重要的作用,它允许程序通过读取和写入文件来持久化数据,实现数据的长期保存和共享。文件读写是许多应用程序的核心功能之一,无论是创建文本文件、二进制文件,还是处理配置文件、日志文件或数据库文件,文件读写都是不可或缺的部分。

System.IO 命名空间有各种不同的类,用于执行各种文件操作,如创建和删除文件、读取或写入文件,关闭文件等。

2、相关类介绍

文件流对象(FileStream)在读写字节的效率是相当高的,但是在处理其他类型的数据时会比较麻烦,所以就出现了二进制读写器(BinaryReader和BinaryWriter)和文本读写器(StreamReader和StreamWriter)来解决这一问题。

System.IO 命名空间中常用的类:
在这里插入图片描述
在这里插入图片描述

3、代码示例

3.1 FileStream(流文件)

在这里插入图片描述

  • 例子1:
using System;
using System.IO;

namespace FileIOApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            for (int i = 0; i <= 100; i++)
            {
                fs.WriteByte((byte)i);
            }

            fs.Position = 0;
            for (int i = 0; i <= 100; i++)
            {
                Console.Write(fs.ReadByte() + " ");
            }

            fs.Close();
            Console.ReadKey();
        }
    }
}

在这里插入图片描述
在这里插入图片描述

  • 例子2:

3.2 StreamReader / StreamWriter (文本文件)

文本文件的读写。
StreamReader 和 StreamWriter 类有助于完成文本文件的读写。
这些类从抽象基类 Stream 继承,Stream 支持文件流的字节读写。

3.2.1 StreamReader

在这里插入图片描述

  • 代码例子1:
using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (StreamReader sr = new StreamReader("./飞鸟集.txt"))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line); 
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

运行结果如下:

在这里插入图片描述

在这里插入图片描述

  • 代码例子2:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 打开文件并创建FileStream对象
        using (FileStream fileStream = new FileStream("飞鸟集.txt", FileMode.Open, FileAccess.Read))
        {
            // 读取文件内容
            StreamReader reader = new StreamReader(fileStream);
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}

在这里插入图片描述

  • 代码例子3:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 打开文件并创建FileStream对象
        using (FileStream fileStream = new FileStream("飞鸟集.txt", FileMode.Open, FileAccess.Read))
        {
            // 读取文件内容
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                // 处理读取的数据
                string content = System.Text.Encoding.Default.GetString(buffer, 0, bytesRead);
                // string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.Write(content);
            }
        }
    }
}

在这里插入图片描述

  • 代码例子4:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 打开文件流并创建StreamReader对象用于读取文件内容
        using (FileStream fs = new FileStream("example.txt", FileMode.Open, FileAccess.Read))
        using (StreamReader reader = new StreamReader(fs))
        {
            // 读取文件内容并输出到控制台
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

3.2.2 StreamWriter

在这里插入图片描述

  • 测试代码1:
using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[] { "hello", "爱看书的小沐" };

            // 通过 StreamWriter 类的实例化进行打开文件
            using (StreamWriter sw = new StreamWriter("test.txt"))
            {
                foreach (string s in names)
                {
                    sw.WriteLine(s);
                }
            }

            string line = "";
            // 通过 StreamReader 类的实例化进行打开文件
            using (StreamReader sr = new StreamReader("test.txt"))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
            Console.ReadKey();
        }
    }
}

运行结果如下:
在这里插入图片描述

  • 测试代码2:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string content = "Hello, 爱看书的小沐.";

        // 打开文件并创建FileStream对象
        using (FileStream fileStream = new FileStream("test.txt", FileMode.Create, FileAccess.Write))
        {
            // 将内容转换为字节数组
            byte[] buffer = System.Text.Encoding.Default.GetBytes(content);
            // 写入文件
            fileStream.Write(buffer, 0, buffer.Length);
        }
    }
}
  • 测试代码3:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string content = "Hello, 爱看书的小沐.";

        // 打开文件并创建StreamWriter对象
        using (StreamWriter writer = new StreamWriter("test.txt"))
        {
            // 写入文件
            writer.Write(content);
        }
    }
}
  • 测试代码4:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 打开文件流并创建StreamWriter对象用于写入文件内容
        using (FileStream fs = new FileStream("example.txt", FileMode.OpenOrCreate, FileAccess.Write))
        using (StreamWriter writer = new StreamWriter(fs))
        {
            // 写入文件内容
            writer.WriteLine("Hello, World!");
            writer.WriteLine("This is a sample text.");
        }
    }
}

3.3 BinaryReader / BinaryWriter (二进制文件)

BinaryReader 和 BinaryWriter 类用于二进制文件的读写。

3.3.1 BinaryReader

BinaryReader 类用于从文件读取二进制数据。
一个 BinaryReader 对象通过向它的构造函数传递 FileStream 对象而被创建。
在这里插入图片描述

3.3.2 BinaryWriter

BinaryWriter 类用于向文件写入二进制数据。
一个 BinaryWriter 对象通过向它的构造函数传递 FileStream 对象而被创建。

在这里插入图片描述

  • 代码测试1:
using System;
using System.IO;

namespace BinaryFileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            BinaryWriter bw;
            BinaryReader br;
            int i = 25;
            double d = 3.14157;
            bool b = true;
            string s = "爱看书的小沐";

            // 创建文件
            try
            {
                bw = new BinaryWriter(new FileStream("mydata.dat",
                FileMode.Create));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot create file.");
                return;
            }
            // 写入文件
            try
            {
                bw.Write(i);
                bw.Write(d);
                bw.Write(b);
                bw.Write(s);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot write to file.");
                return;
            }

            bw.Close();

            // 读取文件
            try
            {
                br = new BinaryReader(new FileStream("mydata.dat",
                FileMode.Open));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot open file.");
                return;
            }
            try
            {
                i = br.ReadInt32();
                Console.WriteLine("Integer data: {0}", i);
                d = br.ReadDouble();
                Console.WriteLine("Double data: {0}", d);
                b = br.ReadBoolean();
                Console.WriteLine("Boolean data: {0}", b);
                s = br.ReadString();
                Console.WriteLine("String data: {0}", s);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot read from file.");
                return;
            }
            br.Close();

            Console.ReadKey();
        }
    }
}

运行结果如下:
在这里插入图片描述
在这里插入图片描述

  • 代码测试2:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.bin";

        // 写入二进制文件
        using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
        {
            int intValue = 42;
            double doubleValue = 3.14;
            string stringValue = "Hello, Binary World!";

            writer.Write(intValue);
            writer.Write(doubleValue);
            writer.Write(stringValue);
        }

        // 读取二进制文件
        using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
        {
            int intValue = reader.ReadInt32();
            double doubleValue = reader.ReadDouble();
            string stringValue = reader.ReadString();

            Console.WriteLine($"Read values: {intValue}, {doubleValue}, {stringValue}");
        }
    }
}

3.4 DirectoryInfo

使用 DirectoryInfo 类处理目录。
DirectoryInfo 类派生自 FileSystemInfo 类。
提供了各种用于创建、移动、浏览目录和子目录的方法。
该类不能被继承。
在这里插入图片描述

3.5 FileInfo

使用 FileInfo 类处理文件。
FileInfo 类派生自 FileSystemInfo 类。
提供了用于创建、复制、删除、移动、打开文件的属性和方法,且有助于 FileStream 对象的创建。
该类不能被继承。
在这里插入图片描述

  • 测试代码1:
    显示当前目录的所有文件名,及各个文件大小。
using System;
using System.IO;

namespace WindowsFileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个 DirectoryInfo 对象
            DirectoryInfo mydir = new DirectoryInfo(@"./");

            // 获取当前目录中的文件以及它们的名称和大小
            FileInfo[] f = mydir.GetFiles();
            foreach (FileInfo file in f)
            {
                Console.WriteLine("File Name: {0} Size: {1}",
                    file.Name, file.Length);
            }
            Console.ReadKey();
        }
    }
}

运行结果如下:
在这里插入图片描述

3.6 Directory

在这里插入图片描述
以下示例演示如何从目录中检索所有文本文件并将其移动到新目录。 移动文件后,它们不再存在于原始目录中。

  • 代码测试:
using System;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\current";
            string archiveDirectory = @"C:\archive";

            try
            {
                var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt");

                foreach (string currentFile in txtFiles)
                {
                    string fileName = currentFile.Substring(sourceDirectory.Length + 1);
                    Directory.Move(currentFile, Path.Combine(archiveDirectory, fileName));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

3.7 File

在这里插入图片描述

  • 测试代码
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @".\飞鸟集.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string createText = "Hello and Welcome" + Environment.NewLine;
            File.WriteAllText(path, createText, Encoding.UTF8);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText, Encoding.UTF8);

        // Open the file to read from.
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}

在这里插入图片描述

3.8 Exception

using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // 打开文件流并创建StreamReader对象用于读取文件内容
            using (FileStream fs = new FileStream("example.txt", FileMode.Open, FileAccess.Read))
            using (StreamReader reader = new StreamReader(fs))
            {
                // 读取文件内容并输出到控制台
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine("文件不存在:" + ex.Message);
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("无访问权限:" + ex.Message);
        }
        catch (IOException ex)
        {
            Console.WriteLine("文件读取错误:" + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("其他错误:" + ex.Message);
        }
    }
}

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

  • 20
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值