StreamWriter类的一般使用方法
理解StreamWriter可以对照StreamReader类来进行,因为他们只是读写的方式不同,一个是读,一个是写,其他的差别不是特别大。
StreamWriter继承于抽象类TextWriter,是用来进行文本文件字符流写的类。
它是按照一种特定的编码从字节流中写入字符,其常用的构造函数如下:
public StreamWriter (string path)//1
public StreamWriter (string path,bool append)//2
public StreamWriter (string path,bool append,Encoding encoding)//3
第1个构造函数,是以默认的形式进行,字符的编码依旧是UTF-8.
第2个构造函数,是1的具体话,引入了一个参数append,这个参数决定了当文件存在的时候,是覆盖还是追加,如果为false,则是覆盖,如果为true,则是追加,1的本质是public StreamWriter (string path,false)
第三个构造函数是2的具体化,引入了具体的字符编码Encoding,默认的情况是UTF-8。
如果文件不存在,会自动创建文件。
StreamWriter的两个重要的方法是Write()与WriteLine()。下面具体来说一说。
Write(string)方法是直接将string写入到文件中,而WriteLine(string)写完string加了一个回车换行,参见下面的代码的区别:

using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
try
{
using (StreamWriter sw= new StreamWriter("TestFile.txt"))
{
string str1 = "abc";
string str2 = "def";
sw.Write(str1);
sw.Write(str2);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
try
{
using (StreamWriter sw= new StreamWriter("TestFile.txt"))
{
string str1 = "abc";
string str2 = "def";
sw.WriteLine(str1);
sw.WriteLine(str2);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
打开文件TestFile.txt就能找到它们的区别了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!