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() 方法逐行读取文件中的内容,并在控制台打印出来。

相关推荐
小码编匠2 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫9 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez201015 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
東雪蓮☆2 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust