蓝色天空网mbsky.com · 知识 · 实践 · 创造C# · 本地阅读预览
教程 / 后端开发 / C#

C# 文件的输入与输出

系统梳理 C# 文件与字节流模型、System.IO 15 个核心非抽象类、FileStream 构造及 FileMode/FileAccess/FileShare 枚举语义,并在隔离临时目录内通过本地 csc.exe 实测全部读写与清理流程。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

文件、字节流与 System.IO 核心类体系

文件是磁盘上按路径与名称持久化组织的数据集合;当程序打开文件进行读取或写入时,它便抽象为顺序传递的字节序列——流(Stream)。输入流用于从外部数据源读取字节到内存,输出流用于将内存字节写入目标介质。

`System.IO` 命名空间提供了一整套覆盖字节流、字符流、二进制编解码以及目录/文件/驱动器元数据的类型。下表汇总 15 个最常用的非抽象 I/O 类及其职责边界。

FileStream 构造参数与三组核心枚举

`FileStream` 继承自抽象基类 `Stream`,支持对磁盘文件进行任意偏移位置的随机字节读写。创建对象时除文件路径外,通常按需组合 `FileMode`、`FileAccess` 与 `FileShare` 三个枚举参数(例如 `new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read)`)。工程中务必将 `FileStream` 包裹在 `using (...)` 语句块中,以确保即使发生异常也能自动释放操作系统文件句柄。

三组枚举分别控制打开方式、当前句柄权限及并发共享策略:`FileMode` 包含 6 项成员——`Append` 打开已有文件并定位到末尾(不存在则新建)、`Create` 覆盖重建新文件、`CreateNew` 仅创建新文件(已存在则抛 `IOException`)、`Open` 打开已有文件(不存在则抛 `FileNotFoundException`)、`OpenOrCreate` 存在即打开否则新建、`Truncate` 打开已有文件并将长度截断为 `0` 字节(不存在抛异常);`FileAccess` 包含 `Read`、`Write` 与 `ReadWrite` 三项;`FileShare` 包含 `Inheritable`、`None`、`Read`、`Write`、`ReadWrite` 与 `Delete` 六项,用于约束当前句柄关闭前其他请求能否同时打开或删除该文件。详见下方参数枚举参考表。

FileStream 字节读写实测与进阶文件操作主题

顺序写入再回退读取是验证 `FileStream` 位置指针(`Position`)与流尾哨兵的经典场景:以 `FileMode.OpenOrCreate` 和 `FileAccess.ReadWrite` 打开文件,循环调用 `WriteByte` 写入 `1` 至 `20`,再将 `Position` 重置为 `0` 后连续调用 21 次 `ReadByte()`。前 20 次依次返回 `1..20`,第 21 次到达流末尾(EOF)时返回 `-1`(因此 `ReadByte()` 返回类型为 `int` 而非 `byte`)。本站隔离临时目录实测精确复现了 `1 2 ... 20 -1` 并在 `finally` 中递归清理临时文件。

在掌握底层字节流后,实际业务通常按场景选用更高层封装:文本文件读写交由 `StreamReader`/`StreamWriter` 自动处理字符编码与换行;结构化原始类型二进制读写交由 `BinaryReader`/`BinaryWriter`;目录遍历与路径组合则使用 `Directory`/`DirectoryInfo`、`File`/`FileInfo`、`Path` 与 `DriveInfo` 完成。三大进阶主题详见第三张参考表,全部对应类均已在本机隔离目录中实测通过。

System.IO 命名空间 15 个常用非抽象类参考表

I/O 类核心职责典型场景与实测验证
`BinaryReader`从底层字节流按原始类型读取二进制数据实测按序还原 `Int32`/`Double`/`String`
`BinaryWriter`将原始类型值以紧凑二进制格式写入流实测经由 `BufferedStream` 写入 `42`、`3.5`、`"OK"`
`BufferedStream`为底层流叠加内存缓冲层以减少系统调用频次实测包装 `FileStream` 缓冲写入后完整落盘
`Directory`提供创建、移动、枚举与删除目录的静态方法实测创建与递归清理隔离临时子目录
`DirectoryInfo`面向具体目录实例执行查询与操作(减少重复路径检查)实测核验子目录 `Exists == True`
`DriveInfo`查询逻辑磁盘驱动器的就绪状态、格式与剩余空间实测查询临时目录所在盘符 `IsReady == True`
`File`提供一次性文本/字节读写、复制与删除的静态快捷方法实测 `WriteAllText`/`ReadAllText` UTF-8 往返
`FileInfo`封装单个文件实例的属性(长度、时间戳等)与操作实测新建 5 字节文件 `Length == 5`
`FileStream`支持文件任意位置随机读写的底层字节流实测 `WriteByte`/`Position=0`/`ReadByte` 及 EOF `-1`
`MemoryStream`以后备内存数组为存储介质的随机访问字节流实测写入 `"MEM"` 后 `ToArray()` 还原一致
`Path`跨平台安全拼接路径并提取扩展名、文件名与根目录实测 `Path.Combine`、`GetExtension(".txt")` 与 `GetPathRoot`
`StreamReader`按指定字符编码从字节流逐行或全文读取字符实测 UTF-8 读取 `"hello-csharp"`
`StreamWriter`按指定字符编码向字节流写入格式化文本实测 UTF-8 写入单行文本并刷新落盘
`StringReader`将内存中的 `string` 作为字符读取器流式读取实测读取 `StringWriter` 缓冲内容得 `"BUF"`
`StringWriter`将字符输出写入内部 `StringBuilder` 缓冲区实测写入 `"BUF"` 并转换为字符串

FileStream 构造三组核心枚举参数对照表

参数枚举成员清单与关键语义实测核验要点
`FileMode``Append`、`Create`、`CreateNew`、`Open`、`OpenOrCreate`、`Truncate`(共 6 项),决定新建、覆盖、截断或追加打开行为实测 `Open` 缺文件抛 `FileNotFoundException`、`CreateNew` 遇同名抛 `IOException`、`Truncate`+`Append` 得 `"XYZ"`
`FileAccess``Read`、`Write`、`ReadWrite`(共 3 项),限定当前流实例允许执行的读写方向实测枚举成员数 `3`,配合 `FileStream` 读写权限一致
`FileShare``Inheritable`、`None`、`Read`、`Write`、`ReadWrite`、`Delete`(共 6 项),控制句柄未关闭前其他打开请求的共享权限实测 `FileShare.None` 阻断二次只读打开(抛 `IOException`),`FileShare.Read` 允许双只读句柄并发访问

C# 高级文件与文件系统操作主题导航表

主题核心类库与能力范围对应实测用例
文本文件的读写基于 `StreamReader` 与 `StreamWriter` 按编码(如 UTF-8)读写文本行已在 `text_and_binary_io_streams` 实测往返
二进制文件的读写基于 `BinaryReader` 与 `BinaryWriter` 紧凑读写基元类型原始字节已在 `text_and_binary_io_streams` 实测往返
Windows 文件系统的操作基于 `Directory`/`DirectoryInfo`、`File`/`FileInfo`、`Path`、`DriveInfo` 管理目录树与文件元数据已在 `filesystem_path_directory_file_info` 实测通过

运行 csc.exe (.NET Framework 4.x) FileStream、三大枚举、文本/二进制流与临时文件系统实测

csharp · 阅读源码
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace CSharpFileIoLab
{
    internal class Program
    {
        private static string Esc(string s)
        {
            if (s == null) return "null";
            StringBuilder sb = new StringBuilder("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\\': sb.Append("\\\\"); break;
                    case '"': sb.Append("\\\""); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    default:
                        if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
                        else sb.Append(c);
                        break;
                }
            }
            sb.Append("\"");
            return sb.ToString();
        }

        private static string CaseJson(string name, string summary, string expected, string actual)
        {
            bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
            return string.Format(
                "{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
                Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
            );
        }

        public static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            List<string> cases = new List<string>();
            string tempDir = Path.Combine(Path.GetTempPath(), "csharplab-" + Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(tempDir);

            try
            {
                // Case 1: FileStream WriteByte / Position=0 / ReadByte including -1 EOF
                string datPath = Path.Combine(tempDir, "test.dat");
                List<string> readTokens = new List<string>();
                using (FileStream fs = new FileStream(datPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    for (int i = 1; i <= 20; i++)
                    {
                        fs.WriteByte((byte)i);
                    }
                    fs.Position = 0;
                    for (int i = 0; i <= 20; i++)
                    {
                        readTokens.Add(fs.ReadByte().ToString());
                    }
                }
                cases.Add(CaseJson(
                    "filestream_byte_rw_and_eof",
                    "Write bytes 1..20 with FileStream, reset Position=0, and read 21 times yielding 1..20 and -1 EOF",
                    "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1",
                    string.Join(" ", readTokens.ToArray())
                ));

                // Case 2: FileMode, FileAccess, FileShare behaviors
                string modePath = Path.Combine(tempDir, "modes.txt");
                bool openMissingThrew = false;
                try
                {
                    using (new FileStream(modePath, FileMode.Open, FileAccess.Read)) { }
                }
                catch (FileNotFoundException)
                {
                    openMissingThrew = true;
                }

                File.WriteAllText(modePath, "abc", Encoding.UTF8);
                bool createNewThrew = false;
                try
                {
                    using (new FileStream(modePath, FileMode.CreateNew, FileAccess.Write)) { }
                }
                catch (IOException)
                {
                    createNewThrew = true;
                }

                using (FileStream fsTrunc = new FileStream(modePath, FileMode.Truncate, FileAccess.Write))
                {
                    byte[] b = Encoding.ASCII.GetBytes("XY");
                    fsTrunc.Write(b, 0, b.Length);
                }
                using (FileStream fsApp = new FileStream(modePath, FileMode.Append, FileAccess.Write))
                {
                    byte[] b = Encoding.ASCII.GetBytes("Z");
                    fsApp.Write(b, 0, b.Length);
                }
                string modeText = File.ReadAllText(modePath, Encoding.ASCII);

                bool shareNoneBlocked = false;
                using (FileStream lockFs = new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    try
                    {
                        using (new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { }
                    }
                    catch (IOException)
                    {
                        shareNoneBlocked = true;
                    }
                }
                bool shareReadAllowed = false;
                using (FileStream r1 = new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (FileStream r2 = new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        shareReadAllowed = (r1.Length == 3 && r2.Length == 3);
                    }
                }
                int accessCount = Enum.GetNames(typeof(FileAccess)).Length;
                int modeCount = Enum.GetNames(typeof(FileMode)).Length;
                int shareCount = Enum.GetNames(typeof(FileShare)).Length;
                string actual2 = string.Format(
                    "openMiss={0};createNewExist={1};text={2};shareNone={3};shareRead={4};counts={5}/{6}/{7}",
                    openMissingThrew, createNewThrew, modeText, shareNoneBlocked, shareReadAllowed,
                    modeCount, accessCount, shareCount
                );
                cases.Add(CaseJson(
                    "filemode_access_share_enums",
                    "Verify FileMode (Open/CreateNew/Truncate/Append), FileAccess, and FileShare (None vs Read)",
                    "openMiss=True;createNewExist=True;text=XYZ;shareNone=True;shareRead=True;counts=6/3/6",
                    actual2
                ));

                // Case 3: StreamWriter/StreamReader, BinaryWriter/BinaryReader, MemoryStream, BufferedStream, StringWriter/StringReader
                string txtPath = Path.Combine(tempDir, "lines.txt");
                using (StreamWriter sw = new StreamWriter(txtPath, false, Encoding.UTF8))
                {
                    sw.WriteLine("hello-csharp");
                }
                string lineRead;
                using (StreamReader sr = new StreamReader(txtPath, Encoding.UTF8))
                {
                    lineRead = sr.ReadLine();
                }

                string binPath = Path.Combine(tempDir, "vals.bin");
                using (FileStream bfs = new FileStream(binPath, FileMode.Create, FileAccess.Write))
                using (BufferedStream buf = new BufferedStream(bfs))
                using (BinaryWriter bw = new BinaryWriter(buf, Encoding.UTF8))
                {
                    bw.Write(42);
                    bw.Write(3.5);
                    bw.Write("OK");
                }
                int bi;
                double bd;
                string bs;
                using (BinaryReader br = new BinaryReader(File.Open(binPath, FileMode.Open, FileAccess.Read), Encoding.UTF8))
                {
                    bi = br.ReadInt32();
                    bd = br.ReadDouble();
                    bs = br.ReadString();
                }

                string memResult;
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] data = Encoding.ASCII.GetBytes("MEM");
                    ms.Write(data, 0, data.Length);
                    ms.Position = 0;
                    memResult = Encoding.ASCII.GetString(ms.ToArray());
                }

                StringWriter strW = new StringWriter();
                strW.Write("BUF");
                string strR = new StringReader(strW.ToString()).ReadToEnd();

                string actual3 = string.Format("txt={0};bin={1}/{2}/{3};mem={4};str={5}", lineRead, bi, bd, bs, memResult, strR);
                cases.Add(CaseJson(
                    "text_and_binary_io_streams",
                    "Verify StreamReader/Writer, BinaryReader/Writer, BufferedStream, MemoryStream, and StringReader/Writer",
                    "txt=hello-csharp;bin=42/3.5/OK;mem=MEM;str=BUF",
                    actual3
                ));

                // Case 4: Directory, DirectoryInfo, File, FileInfo, Path, DriveInfo
                string subDir = Path.Combine(tempDir, "sub");
                DirectoryInfo di = Directory.CreateDirectory(subDir);
                string sampleFile = Path.Combine(subDir, "item.txt");
                File.WriteAllText(sampleFile, "12345", Encoding.ASCII);
                FileInfo fi = new FileInfo(sampleFile);
                string ext = Path.GetExtension(sampleFile);
                string root = Path.GetPathRoot(tempDir);
                DriveInfo drv = new DriveInfo(root);
                string actual4 = string.Format("dir={0};len={1};ext={2};driveReady={3}", di.Exists, fi.Length, ext, drv.IsReady);
                cases.Add(CaseJson(
                    "filesystem_path_directory_file_info",
                    "Verify Directory/DirectoryInfo, File/FileInfo, Path, and DriveInfo operations inside temp workspace",
                    "dir=True;len=5;ext=.txt;driveReady=True",
                    actual4
                ));
            }
            finally
            {
                if (Directory.Exists(tempDir))
                {
                    Directory.Delete(tempDir, true);
                }
            }

            Console.WriteLine(string.Format(
                "{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
                Environment.Version.ToString(),
                string.Join(",", cases.ToArray())
            ));
        }
    }
}
预期结果 · 待实际运行核验
  • 在自动清理的隔离临时目录内,核对 FileStream 1..20 及 EOF -1、FileMode/FileAccess/FileShare 锁与异常边界、文本/二进制/内存流及目录文件元数据全部通过。
运行 csc.exe (.NET Framework 4.x) FileStream、三大枚举、文本/二进制流与临时文件系统实测

所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

当前源码 SHA256:840072940235eae9c4e659eb440002b86a71a037d514d8c9a694986b2d6af72c

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载C# 文件的输入与输出实验

所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

ZIP SHA256:48d45699b2ea1ca43bca8678a51a5edf30afba04e58b302c6021df4d3a14c4c7

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 `FileStream.ReadByte()` 的返回类型是 `int` 而不是 `byte`?使用 `FileStream` 时为什么推荐用 `using` 块包裹?

展开参考解答

有效字节的取值范围已占满 `0`–`255`,需要额外返回 `-1` 表示已到达流末尾(EOF),因此返回类型为 `int`。`FileStream` 持有非托管操作系统文件句柄,使用 `using` 块可在正常结束或抛出异常时自动调用 `Dispose()` 及时释放句柄,避免文件锁泄漏。

规范与官方依据