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

相关推荐
vortex54 分钟前
探索 Shell:选择适合你的命令行利器 bash, zsh, fish, dash, sh...
linux·开发语言·bash·shell·dash
zzc9217 分钟前
MATLAB仿真生成无线通信网络拓扑推理数据集
开发语言·网络·数据库·人工智能·python·深度学习·matlab
HUN金克斯16 分钟前
C++/C函数
c语言·开发语言·c++
慢半拍iii16 分钟前
数据结构——F/图
c语言·开发语言·数据结构·c++
钢铁男儿19 分钟前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
编程有点难22 分钟前
Python训练打卡Day43
开发语言·python·深度学习
m0_6371469327 分钟前
零基础入门 C 语言基础知识(含面试题):结构体、联合体、枚举、链表、环形队列、指针全解析!
c语言·开发语言·链表
LjQ204036 分钟前
网络爬虫一课一得
开发语言·数据库·python·网络爬虫
你是狒狒吗43 分钟前
TM中,return new TransactionManagerImpl(raf, fc);为什么返回是new了一个新的实例
java·开发语言·数据库