本页说明在 .NET Framework 4.8 窗体(或控制台)项目中用 System.IO 读写文本与二进制文件。目标框架以 LCode 默认的 .NET 4.8 为准;示例写法面向 C# 5.0 与 VB.NET(勿用 C# 6+ 语法如字符串插值、nameof)。操作文案以 LCode 中文界面为准。把文件加入项目见 资源文件;INI 配置见 INI 与 INF;JSON/XML 见 JSON 与 XML 解析。大文件或阻塞读勿卡 UI,见 异步、同步与多线程

选用哪种方式

方式 命名空间 / 类型 适用
File 静态方法 System.IO.File 整文件读入/写出字符串或字节;代码最短,小到中等文件最省事
StreamReader / StreamWriter System.IO 按行或分块读写文本;可指定编码;适合日志、逐行处理
FileStream System.IO.FileStream 二进制、随机访问、与其他流(缓冲、加密包装)组合
提示:窗体项目默认已引用含 System.IO 的框架程序集。代码中 using System.IO; / Imports System.IO 即可,一般不必再「添加引用」。

在 LCode 中使用

  1. 窗体应用入门 建好「Windows 应用程序」。
  2. 在窗体或类中编写读写代码;路径常用 Path.Combine(Application.StartupPath, "data.txt")
  3. 若要把样本文件随程序发布:加入项目后设「复制到输出目录」。详见 资源文件
  4. 菜单 编译 → 编译解决方案F8),再运行验证。

常用 File API

成员 说明
File.Exists(path) 文件是否存在
File.ReadAllText(path) / ReadAllText(path, encoding) 一次读入全部文本
File.WriteAllText(path, contents) / 带 encoding 覆盖写入全部文本(文件不存在则创建)
File.AppendAllText(path, contents) 追加文本到文件末尾
File.ReadAllLines(path) 读入为字符串数组(按行)
File.ReadAllBytes / WriteAllBytes 整文件二进制读写
File.Copy / Move / Delete 复制、移动、删除
Directory.CreateDirectory(path) 确保目录存在(可多级)
Path.Combine / Path.GetFileName 拼接与解析路径,避免手写分隔符
C#
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

string path = Path.Combine(Application.StartupPath, "note.txt");

// 写出(UTF-8)
File.WriteAllText(path, "第一行\r\n第二行", Encoding.UTF8);

// 读入
if (File.Exists(path))
{
    string text = File.ReadAllText(path, Encoding.UTF8);
    MessageBox.Show(text);
}

// 追加
File.AppendAllText(path, "\r\n追加一行", Encoding.UTF8);
VB.NET
Imports System
Imports System.IO
Imports System.Text
Imports System.Windows.Forms

Dim path As String = Path.Combine(Application.StartupPath, "note.txt")

' 写出(UTF-8)
File.WriteAllText(path, "第一行" & vbCrLf & "第二行", Encoding.UTF8)

' 读入
If File.Exists(path) Then
    Dim text As String = File.ReadAllText(path, Encoding.UTF8)
    MessageBox.Show(text)
End If

' 追加
File.AppendAllText(path, vbCrLf & "追加一行", Encoding.UTF8)

StreamReader / StreamWriter

适合按行处理或需要显式控制编码、缓冲的场景。用 using / Using 确保关闭句柄。

成员 说明
StreamReader.ReadLine 读一行;文件结束返回 null(VB 为 Nothing
StreamReader.ReadToEnd 从当前位置读到末尾
StreamWriter.Write / WriteLine 写文本 / 写一行并换行
构造参数 Encoding 指定读写编码;中文日志常用 UTF-8 或 GB2312
C#
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

string path = Path.Combine(Application.StartupPath, "lines.txt");

using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
{
    sw.WriteLine("alpha");
    sw.WriteLine("beta");
}

using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        // 逐行处理
        Console.WriteLine(line);
    }
}
VB.NET
Imports System
Imports System.IO
Imports System.Text
Imports System.Windows.Forms

Dim path As String = Path.Combine(Application.StartupPath, "lines.txt")

Using sw As New StreamWriter(path, False, Encoding.UTF8)
    sw.WriteLine("alpha")
    sw.WriteLine("beta")
End Using

Using sr As New StreamReader(path, Encoding.UTF8)
    Dim line As String = sr.ReadLine()
    While line IsNot Nothing
        ' 逐行处理
        Console.WriteLine(line)
        line = sr.ReadLine()
    End While
End Using

FileStream(二进制)

需要字节级读写、指定 FileMode/FileAccess,或与其他流组合时用 FileStream

成员 / 枚举 说明
FileMode.Create / Open / Append 创建或打开方式
FileAccess.Read / Write / ReadWrite 访问权限
Read / Write 读写字节缓冲区;注意返回的实际字节数
Seek / Position 随机定位(支持寻址的流)
C#
using System;
using System.IO;
using System.Windows.Forms;

string path = Path.Combine(Application.StartupPath, "blob.bin");
byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 };

using (FileStream fs = new FileStream(
    path, FileMode.Create, FileAccess.Write))
{
    fs.Write(data, 0, data.Length);
}

byte[] buffer = new byte[4];
using (FileStream fs = new FileStream(
    path, FileMode.Open, FileAccess.Read))
{
    int n = fs.Read(buffer, 0, buffer.Length);
    // n 为实际读到的字节数
}
VB.NET
Imports System
Imports System.IO
Imports System.Windows.Forms

Dim path As String = Path.Combine(Application.StartupPath, "blob.bin")
Dim data As Byte() = New Byte() {&H1, &H2, &H3, &H4}

Using fs As New FileStream(path, FileMode.Create, FileAccess.Write)
    fs.Write(data, 0, data.Length)
End Using

Dim buffer(3) As Byte
Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
    Dim n As Integer = fs.Read(buffer, 0, buffer.Length)
    ' n 为实际读到的字节数
End Using

注意与易错点

说明
编码 读写双方编码须一致;中文乱码多半是 UTF-8 / 系统 ANSI 混用。明确传入 Encoding.UTF8 等。
路径 相对路径相对进程当前目录,不一定是 exe 目录。窗体应用优先 Application.StartupPath + Path.Combine
未关闭流 忘记 using/Dispose 会导致文件被占用、后续打不开。读写后务必释放。
UI 线程 大文件同步读会卡住窗体;放到后台线程或异步模式,见 异步、同步与多线程
权限 / 占用 无写权限、文件被其他进程独占都会抛 IOException / UnauthorizedAccessException,应捕获并提示用户。
C# 语言版本 LCode / .NET 4.8 按 C# 5.0:勿用 $"…"nameof?. 等。

相关阅读