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(共享)

一般用 None 或 Read

六、为什么都用 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

相关推荐
wangchunyu1146 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
程序 代码狂人7 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
meiying88388 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
@大迁世界9 小时前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper9 小时前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
学逆向的9 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
低调滴开发10 小时前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust
CodeYp201910 小时前
第15讲:二叉搜索树
开发语言·c++·二叉搜索树
猫猫.15310 小时前
HashTable、HashMap、ConcurrentHashMap 核心区别总结
java·开发语言·java-ee
乌暮11 小时前
综合案例:宠物电商系统
java·开发语言·spring·mvc·restful·1024程序员节