C# 文件输入输出 精简理解

目录

[常用 4 个工具](#常用 4 个工具)

[一、File 静态类(常用)](#一、File 静态类(常用))

[二、文本文件专业读写:StreamReader / StreamWriter](#二、文本文件专业读写:StreamReader / StreamWriter)

三、FileStream(读写字节)

[四、文件夹操作 Directory](#四、文件夹操作 Directory)

[五、3 个枚举(必须懂)](#五、3 个枚举(必须懂))

[1. FileMode(怎么打开文件)](#1. FileMode(怎么打开文件))

[2. FileAccess(权限)](#2. FileAccess(权限))

[3. FileShare(共享)](#3. FileShare(共享))

[六、为什么都用 using?](#六、为什么都用 using?)


C# 文件操作都在 System.IO 命名空间

必须引用 using System.IO;

文件操作 = 读 + 写 + 文件 / 文件夹管理

常用 4 个工具

  • File :静态类,一次性读写文件(最简单)
  • StreamReader / StreamWriter :读写文本文件
  • FileStream :读写字节(图片、视频、大文件)
  • Directory :操作文件夹

一、File 静态类(常用)

  1. 读文本
cs 复制代码
string content = File.ReadAllText("a.txt");
  1. 写文本(会覆盖)
cs 复制代码
File.WriteAllText("a.txt", "你好,C#");
  1. 追加文本
cs 复制代码
File.AppendAllText("a.txt", "追加的内容");
  1. 读所有行
cs 复制代码
string[] lines = File.ReadAllLines("a.txt");
  1. 复制、删除、移动
cs 复制代码
File.Copy("a.txt", "b.txt");
File.Delete("test.txt");
File.Move("a.txt", "new/a.txt");

二、文本文件专业读写:StreamReader / StreamWriter

适合大文件、逐行读写

cs 复制代码
using (StreamReader sr = new StreamReader("a.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
cs 复制代码
using (StreamWriter sw = new StreamWriter("a.txt"))
{
    sw.WriteLine("第一行");
    sw.WriteLine("第二行");
}

三、FileStream(读写字节)

用于图片、视频、二进制文件。

cs 复制代码
using (FileStream fs = new FileStream("a.dat", FileMode.OpenOrCreate))
{
    // 写字节
    byte[] data = new byte[] { 10, 20, 30 };
    fs.Write(data, 0, data.Length);
}

四、文件夹操作 Directory

cs 复制代码
// 创建文件夹
Directory.CreateDirectory("myfolder");

// 判断是否存在
bool exists = Directory.Exists("myfolder");

// 获取文件夹下所有文件
string[] files = Directory.GetFiles("myfolder");

五、3 个枚举(必须懂)

1. FileMode(怎么打开文件)

  • Open:打开(不存在报错)
  • Create:创建(存在覆盖)
  • OpenOrCreate:不存在就创建
  • Append:追加到末尾

2. FileAccess(权限)

  • Read
  • Write
  • ReadWrite

3. FileShare(共享)

一般用 NoneRead

六、为什么都用 using?

因为文件是系统资源 ,using 会自动关闭文件,不占内存、不报错。

cs 复制代码
using (var fs = new FileStream(...))
{
    // 自动释放
}

C# 文件 IO 实操练习题 5道https://blog.csdn.net/m0_71071209/article/details/161318394?spm=1001.2014.3001.5502

相关推荐
老王爱玩车1 小时前
深入理解指针2
c语言·开发语言·学习
quantdash_cc1 小时前
股票历史数据为什么比实时行情更重要?回测结果失真的根源可能就在 K 线数据
开发语言·python·数据分析·量化交易·股票数据·quantdash
光电的一只菜鸡2 小时前
为什么调整LSC会对AF产生影响
android·开发语言·kotlin
zhangjw342 小时前
第47篇:Java综合实战:电商秒杀系统(高并发场景)
java·开发语言
FOAF-lambda2 小时前
uiautomation-new 控件方位的使用
开发语言·python
OKkankan2 小时前
LangChain能力详解!:从工具调用到 LangSmith——让聊天模型具备实时交互能力!
开发语言·python·langchain
richard_yuu2 小时前
AOI 实战第五篇:c_broken 漏检严重,V4 迭代背后的权衡
开发语言·深度学习·yolo
m0_734571762 小时前
深入理解C++ 析构函数<一>基本概念
开发语言·c++
滕州市燕猫虎计算机科技工作室个体工商户3 小时前
Java面试题汇总
java·开发语言