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

相关推荐
神秘人X70720 分钟前
Linux高效备份:rsync + inotify实时同步
linux·服务器·rsync
ankleless1 小时前
Python 数据可视化:Matplotlib 与 Seaborn 实战
开发语言·python
Gavin_9152 小时前
一文速通Ruby语法
开发语言·ruby
搞一搞汽车电子2 小时前
vs studio 2017项目不支持studio vs2022
开发语言
witkey_ak98962 小时前
python 可迭代对象相关知识点
开发语言·python
呼啦啦啦啦啦啦啦啦2 小时前
synchronized锁,ReentrantLock 锁
开发语言·
听风的码3 小时前
Vue2封装Axios
开发语言·前端·javascript·vue.js
m0_748254094 小时前
2025最新华为云国际版注册图文流程-不用绑定海外信用卡注册
服务器·数据库·华为云
MUY09904 小时前
应用控制技术、内容审计技术、AAA服务器技术
运维·服务器
素界UI设计4 小时前
建筑行业变革:用Three.js构建BIM数据可视化孪生平台
开发语言·javascript·信息可视化