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

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

地理数据 vs. 3D数据

在表示我们周围的物理世界时&#xff0c;地理空间数据和 3D 建筑数据是两个最常见的选择。 他们在各个行业和项目中发挥着至关重要的作用。 从构建数字孪生到可视化城市景观和创建沉浸式应用程序。 尽管地理空间和 3D 建筑数据有相似之处&#xff0c;但它们不可互换。 虽然地…

国投用什么档案管理系统好

国投适合使用综合档案管理系统。这是因为国投通常规模较大&#xff0c;涉及的业务范围也比较广泛&#xff0c;包括行政管理、财务管理、人力资源管理等。 玖拓智能综合档案管理系统能够整合这些不同部门的档案管理需求&#xff0c;提供统一的档案管理平台&#xff0c;方便国投内…

蓝桥杯 填空 卡片

蓝桥杯 填空题 卡片 解题思路&#xff1a; 我们只需要消耗完卡片的个数即可。 代码示例&#xff1a; #include<bits/stdc.h> using namespace std; int a[10]; bool isEnd(){for(int i0;i<10;i){if(a[i]-1)return false;}return true; } bool getN(int x){while(x){i…

SQLiteC/C++接口详细介绍之sqlite3类(五)

快速跳转文章列表&#xff1a;SQLite—系列文章目录 上一篇&#xff1a;SQLiteC/C接口详细介绍之sqlite3类&#xff08;四&#xff09; 下一篇&#xff1a;SQLiteC/C接口详细介绍之sqlite3类&#xff08;六&#xff09;&#xff08;未发表&#xff09; 14.sqlite3_busy_handle…

2024年云仓酒庄:店中店增项新模式,开启葡萄酒文化新篇章

2024云仓酒庄&#xff1a;店中店增项新模式&#xff0c;开启葡萄酒文化新篇章 在葡萄酒行业蓬勃发展的今天&#xff0c;云仓酒庄以其独特的经营模式和创新思维&#xff0c;在市场中脱颖而出。2024年&#xff0c;云仓酒庄继续深化其战略布局&#xff0c;不仅在多地开设酒庄实体…

运维专题.Docker+Nginx服务器的SSL证书安装

运维专题 DockerNginx服务器的SSL证书安装 - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:https://blog.csdn.net/q…

【C++】—— 代理模式

目录 &#xff08;一&#xff09;什么是代理模式 &#xff08;二&#xff09;为什么使用代理模式 &#xff08;三&#xff09;代理模式实现步奏 &#xff08;四&#xff09;代码示例 &#xff08;五&#xff09;代理模式优缺点 &#xff08;一&#xff09;什么是代理模式 …

备考2025年AMC8竞赛:吃透2000-2024年600道真题(免费赠送真题)

我们继续来随机看五道AMC8的真题和解析&#xff0c;根据实践经验&#xff0c;对于想了解或者加AMC8美国数学竞赛的孩子来说&#xff0c;吃透AMC8历年真题是备考最科学、最有效的方法之一。 即使不参加AMC8竞赛&#xff0c;吃透了历年真题600道和背后的知识体系&#xff0c;那么…

软考高级:需求变更管理过程概念和例题

作者&#xff1a;明明如月学长&#xff0c; CSDN 博客专家&#xff0c;大厂高级 Java 工程师&#xff0c;《性能优化方法论》作者、《解锁大厂思维&#xff1a;剖析《阿里巴巴Java开发手册》》、《再学经典&#xff1a;《Effective Java》独家解析》专栏作者。 热门文章推荐&am…

C++学习随笔(4)——类和对象的初探

本章我们来初步学习一下C中的类和对象&#xff01; 目录 1.类的引入 2.类的定义 类的两种定义方式&#xff1a; 3.类的访问限定符及封装 3.1 访问限定符 3.2 封装 4.类的作用域 5.类的实例化 6.类对象模型 6.1 如何计算类对象的大小 6.2 类对象的存储方式猜测 6.3 …

这个学习Python的神仙网站,后悔没早点发现

Python 作为时下最流行的编程语言&#xff0c;很多初学者都将它作为自学编程的首选。不管是有编程经验的开发者&#xff0c;还是新手小白&#xff0c;在这个 AIGC 时代&#xff0c; Python 都可以带你探索新世界。 入门 Python 绝非难事&#xff0c;但如何让自己坚持学下去是如…

用虚拟机安装win10超详细教程。

前言&#xff1a;安装中有任何疑问&#xff0c;可以在评论区提问&#xff0c;博主身经百战会快速解答小伙伴们的疑问 BT、迅雷下载win10镜像&#xff08;首先要下载win10的镜像&#xff09;&#xff1a;ed2k://|file|cn_windows_10_business_editions_version_1903_updated_sep…

Jmeter---跨越线程组传值

1. 创建两个线程组&#xff0c;并添加请求&#xff0c;设置变量并将其设置为全局变量 2. 设置全局变量&#xff1a;使用函数助手的 setProperty 函数&#xff0c;填写相应内容 3. 设置全局变量&#xff1a;创建一个beanShell&#xff0c;把函数生成的内容粘贴过来 4. 获取全局变…

六 超级数据查看器 讲解稿 详情1 概述

六 超级数据查看器 讲解稿 详情1 概述 点此此处 以新界面 打开B站 当前视频教程 APP下载地址 百度 下载地址 ​ 讲解稿全文&#xff1a; 大家好&#xff0c;今天我们讲解一下超级数据查看器详情界面。由于内容较多&#xff0c;讲解要分为7集&#xff0c;这是第一集 首…

【leetcode热题】寻找旋转排序数组中的最小值 II

难度&#xff1a; 困难通过率&#xff1a; 38.7%题目链接&#xff1a;. - 力扣&#xff08;LeetCode&#xff09; 题目描述 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如&#xff0c;数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的…

FastWiki v0.1.0发布!新增超多功能

FastWiki 发布 v0.1.0 https://github.com/239573049/fast-wiki/releases/tag/v0.1.0 更新日志 兼容OpenAI接口格式删除Blazor版本UI删除useEffect,解决可能存在问题的bug修复对话可以看到所有对话Merge branch ‘master’ of https://gitee.com/hejiale010426/fast-wiki更新…

搭建Hadoop3.x完全分布式集群

零、资源准备 虚拟机相关&#xff1a; VMware workstation 16&#xff1a;虚拟机 > vmware_177981.zipCentOS Stream 9&#xff1a;虚拟机 > CentOS-Stream-9-latest-x86_64-dvd1.iso Hadoop相关 jdk1.8&#xff1a;JDK > jdk-8u261-linux-x64.tar.gzHadoop 3.3.6&am…

软考高级:系统工程方法(霍尔三维结构、切克兰德方法等)概念和例题

作者&#xff1a;明明如月学长&#xff0c; CSDN 博客专家&#xff0c;大厂高级 Java 工程师&#xff0c;《性能优化方法论》作者、《解锁大厂思维&#xff1a;剖析《阿里巴巴Java开发手册》》、《再学经典&#xff1a;《Effective Java》独家解析》专栏作者。 热门文章推荐&am…

Python (用户登录、身份归属地查询添加异常处理、绘制多角星、电影信息提取)

任务一&#xff1a;用户登录 登录系统通常分为普通用户与管理员权限&#xff0c;在用户登录系统时&#xff0c;可以根据自身权限进行选择登录。本任务要求实现一个用户登录的程序&#xff0c;该程序分为管理员用户与普通用户&#xff0c;其中管理员账号密码在程序中设定&#…

04_拖动文件渲染在页面中

新建一个文件夹&#xff0c;跟之前一样&#xff0c;在 Vscode 终端里输入 yarn create electron-app Drag。 在 index.html 添加以下代码&#xff0c;JS 文件夹和 render.js 都是新创建的&#xff1a; 首先&#xff0c;css 文件一般和 html 结合使用&#xff0c;相当于 html 是…