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

文章目录

  • 1、简介
  • 2、相关类介绍
  • 3、代码示例
    • 3.1 FileStream(流文件)
    • 3.2 StreamReader / StreamWriter (文本文件)
      • 3.2.1 StreamReader
      • 3.2.2 StreamWriter
    • 3.3 BinaryReader / BinaryWriter (二进制文件)
      • 3.3.1 BinaryReader
      • 3.3.2 BinaryWriter
    • 3.4 DirectoryInfo
    • 3.5 FileInfo
    • 3.6 Directory
    • 3.7 File
    • 3.8 Exception
  • 结语

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???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/455412.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

2024.03.13作业

要求&#xff1a;设计一个Per类&#xff0c;类中包含私有成员:姓名、年龄、指针成员身高、体重&#xff0c;再设计一个Stu类&#xff0c;类中包含私有成员:成绩、Per类对象p1&#xff0c;设计这两个类的构造函数、析构函数和拷贝构造函数。 #include <iostream> #includ…

初学MyBatis小结

0 简介 MyBatis官网介绍 MyBatis 是一款优秀的持久层框架&#xff0c;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO&#xff08;P…

C语言分析基础排序算法——归并排序

目录 归并排序 递归版本 非递归版本 非递归版本的问题 归并排序小优化 归并排序 归并排序&#xff0c;分为分治以及合并&#xff0c;分治部分可以使用递归或者非递归完成&#xff0c;归并排序的基本思路是&#xff1a;将已有序的子序列合并&#xff0c;得到完全有序的序列…

qiankun:vite/webpack项目配置

相关博文&#xff1a; https://juejin.cn/post/7216536069285429285?searchId202403091501088BACFF113F980BA3B5F3 https://www.bilibili.com/video/BV12T411q7dq/?spm_id_from333.337.search-card.all.click qiankun结构&#xff1a; 主应用base&#xff1a;vue3historyv…

基于SpringCache实现数据缓存

SpringCache SpringCache是一个框架实现了基本注解的缓存功能,只需要简单的添加一个EnableCaching 注解就能实现缓存功能 SpringCache框架只是提供了一层抽象,底层可以切换CacheManager接口的不同实现类即使用不同的缓存技术,默认的实现是ConcurrentMapCacheManagerConcurren…

中间件 | Kafka - [常见问题]

INDEX 1 为什么快2 消息丢失2.1 消息丢失位置2.2 如何避免消息丢失 3 顺序消费 1 为什么快 kafka使用的是基于文件的顺序存储 代价是只能通过offset标记消费情况并总 partition 数越高&#xff0c;性能越下降&#xff0c;可降低一个数量级 每个 partition 的消息会保存在一个独…

C++day3——类中的成员函数

思维导图&#xff1a; 2、设计一个Per类&#xff0c;类中包含私有成员&#xff1a;姓名、年龄、指针成员身高、体重&#xff0c;再设计一个Stu类&#xff0c;类中包含私有成员&#xff1a;成绩、Per类对象p1&#xff0c;设计这两个类的构造函数、析构函数和拷贝构造函数。 #in…

力扣串题:验证回文串2

bool judge(char *s,int m,int n){while(m<n){if(s[m]!s[n]){return false;}m,n--;}return true; } bool validPalindrome(char * s){for(int i0,jstrlen(s)-1;i<j;i,j--){if(s[i]!s[j]){return (judge(s,i1,j)||judge(s,i,j-1));}}return true; }这个题直接背大佬代码吧…

彩虹外链网盘界面UI美化版超级简洁好看

彩虹外链网盘界面UI美化版 彩虹外链网盘&#xff0c;是一款PHP网盘与外链分享程序&#xff0c;支持所有格式文件的上传&#xff0c;可以生成文件外链、图片外链、音乐视频外链&#xff0c;生成外链同时自动生成相应的UBB代码和HTML代码&#xff0c;还可支持文本、图片、音乐、…

Albumentations——广泛应用于工业界、学术界、AI竞赛和开源项目中的CV数据增强工具

Albumentations: fast and flexible image augmentationsDiscover Albumentations: an open-source library offering efficient and customizable image augmentations to boost machine learning and computer vision model performance.https://albumentations.ai/

HM v.16.22 顺序读源码day1---encmain.cpp

文章目录 encmain.cpp引入的库执行主体1. 读取输入的配置文件2. 编码启动和过程计时 实现细节1. cTAppEncTop.parseCfg( argc, argv )&#xff1b;2. df::program_options_lite::ParseFailure;3. EnvVar::printEnvVar();4. EnvVar::printEnvVarInUse();5. printMacroSettings()…

plt保存PDF矢量文件中嵌入可编辑字体(可illustrator编辑)

背景&#xff1a; 用默认 plt.savefig() 保存图片&#xff0c;图中文字是以瞄点保存&#xff0c;而不是以文字格式。在编辑矢量图中&#xff0c;无法调整文字大小和字体。 方法&#xff1a; import matplotlib.pyplot as plt import numpy as np# ------输出的图片为illustr…

RabbitMQ备份交换机与优先级队列

1. 备份交换机 备份交换机可以理解为 RabbitMQ 中交换机的“备胎”&#xff0c;当我们为某一个交换机声明一个对应的备份交换机时&#xff0c;就是为它创建一个备胎&#xff0c;当交换机接收到一条不可路由消息时&#xff0c;将会把这条消息转发到备份交换机中&#xff0c;由备…

数据仓库的基本概念、基本特征、体系结构

个人看书学习心得及日常复习思考记录&#xff0c;个人随笔。 数据仓库的基本概念、基本特征 数据仓库的定义&#xff1a;数据仓库是一个面向主题的、集成的、不可更新的、随时间不断变化的数据集合&#xff0c;用以更好地支持企业或组织的决策分析处理。 数据仓库中数据的4个…

26-Java访问者模式 ( Visitor Pattern )

Java访问者模式 摘要实现范例 访问者模式&#xff08;Visitor Pattern&#xff09;使用了一个访问者类&#xff0c;它改变了元素类的执行算法&#xff0c;通过这种方式&#xff0c;元素的执行算法可以随着访问者改变而改变访问者模式中&#xff0c;元素对象已接受访问者对象&a…

Unity2019.2.x 导出apk 安装到安卓Android12+及以上的系统版本 安装出现-108 安装包似乎无效的解决办法

Unity2019.2.x 导出apk 安装到安卓Android12及以上的系统版本 安装出现-108 安装包似乎无效的解决办法 导出AndroidStudio工程后 需要设置 build.gradle文件 // GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAINbuildscript {repositor…

python-0007-django模版

介绍 模版是对js&#xff0c;html等资源的封装 新建 在项目路径下新建模版文件夹templates&#xff08;可以为其他名称&#xff09;&#xff0c;要是想细分业务的话&#xff0c;还可以在templates路径下继续建文件夹。如下图&#xff1a; 注册模版 在项目的settings找到T…

超越营销:交易性邮件如何塑造现代沟通

在我们的电子邮件自动化系列文章中&#xff0c;我们继续探讨交易性邮件的重要性。这些邮件对于向收件人传递实时更新和可操作信息至关重要&#xff0c;是企业运营不可或缺的一部分。 运营触点 在现代沟通中&#xff0c;交易性邮件扮演着不可或缺的角色&#xff0c;尤其是在企…

String类及其常用方法

文章目录 1.String类的特性与使用1.1 String类的特性1.2 String对象的创建方式1.3 String 的使用&#xff08;不同的拼接操作&#xff09; 2.String常用方法2.1 String的常用方法一2.2 String常用方法二2.3 String常用方法三 1.String类的特性与使用 1.1 String类的特性 Stri…

使用Barrier共享鼠标键盘,通过macos控制ubuntu系统

之前文章写过如何使用barrrier通过windows系统控制ubuntu系统&#xff0c;该文章将详细介绍如何使用barrier通过macos系统控制ubuntu系统 一、macOS安装barrier macOS版本barrier链接 1、双击点开安装包 2、将安装包里的barrier拷贝到macOS的达达->应用程序中 3、在达达…