C# StreamWriter类详细使用

StreamWriter 类是 System.IO 命名空间中的一个用于写入文本到文件的类。它提供了多种方法来写入不同类型的数据到文件中,并且可以指定编码、是否追加等参数。

下面是 StreamWriter 类的一些常见用法:

创建 StreamWriter 实例并写入文件

复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        // 创建一个新的文件并写入文本
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.WriteLine("Hello, world!");
            writer.WriteLine("This is a test.");
        }

        Console.WriteLine("File written successfully.");
    }
}

指定编码和追加模式

复制代码
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        // 指定编码和追加模式
        using (StreamWriter writer = new StreamWriter(filePath, true, Encoding.UTF8))
        {
            writer.WriteLine("Hello, world!");
            writer.WriteLine("This is a test.");
        }

        Console.WriteLine("File written successfully.");
    }
}

写入不同类型的数据

复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        using (StreamWriter writer = new StreamWriter(filePath))
        {
            // 写入字符串
            writer.WriteLine("Hello, world!");

            // 写入整数
            writer.Write("Age: ");
            writer.WriteLine(30);

            // 写入浮点数
            writer.Write("Height: ");
            writer.WriteLine(6.1);

            // 写入多行
            writer.WriteLine("This is a test.");
            writer.WriteLine("Another line.");
        }

        Console.WriteLine("File written successfully.");
    }
}

关闭 StreamWriter

一般情况下,StreamWriterusing 块结束时会自动关闭。如果你手动关闭它,可以调用 Close() 方法:

复制代码
writer.Close();

要读取使用 StreamWriter 写入的文件,你需要使用 StreamReader 类。下面是一个示例,演示了如何使用 StreamReader 读取文件中的内容:

复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        // 读取文件
        using (StreamReader reader = new StreamReader(filePath))
        {
            // 读取并打印每一行
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

在这个示例中,我们首先创建了一个 StreamReader 实例,然后使用 ReadLine() 方法逐行读取文件中的内容,并在控制台打印出来。

相关推荐
茶杯梦轩3 天前
从零起步学习RabbitMQ || 第二章:RabbitMQ 深入理解概念 Producer、Consumer、Exchange、Queue 与企业实战案例
服务器·后端·消息队列
晨星shine4 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530144 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526744 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526744 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang5 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
YuMiao5 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Sinclair8 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
Scout-leaf8 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530148 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net