作者简介:博主是一位.Net开发者,同时也是RPA和低代码平台的践行者。 个人主页:会敲键盘的肘子 系列专栏:.Net实用方法总结 呂专栏简介:博主针对.Net开发和C站问答过程中遇到的问题进行总结,形成本专栏,希望可以帮助到您解决问题。 座右铭:总有一天你所坚持的会反过来拥抱你。

写在前面:

本文主要介绍System.IO命名空间的StreamWriter 类,介绍其常用的方法和示例说明。

本文关键字:System.IO、StreamWriter类、方法示例、C#

文章目录

1️⃣ System.IO命名空间2️⃣ StreamWriter类♈ 定义♉ 构造函数StreamWriter(Stream) 初始化 StreamWriter类的新实例。StreamWriter(String) 使用指定的格式控件初始化 StreamWriter类的新实例StreamWriter(Stream, Encoding) 使用指定的编码及默认的缓冲区大小,为指定的流初始化 StreamWriter 类的新实例StreamWriter(String, Boolean) 用默认编码和缓冲区大小,为指定的文件初始化 StreamWriter 类的一个新实例。 如果该文件存在,则可以将其覆盖或向其追加。 如果该文件不存在,此构造函数将创建一个新文件StreamWriter(Stream, Encoding, Int32) 使用指定的编码及缓冲区大小,为指定的流初始化 StreamWriter 类的新实例StreamWriter(String, Boolean, Encoding) 使用指定的编码和默认的缓冲区大小,为指定的文件初始化 StreamWriter 类的新实例。 如果该文件存在,则可以将其覆盖或向其追加。 如果该文件不存在,此构造函数将创建一个新文件StreamWriter(Stream, Encoding, Int32, Boolean) 使用指定的编码和缓冲区大小,为指定的流初始化 StreamWriter类的新实例,并可以选择保持流处于打开状态StreamWriter(String, Boolean, Encoding, Int32) 使用指定编码和缓冲区大小,为指定路径上的指定文件初始化 StreamWriter类的新实例。 如果该文件存在,则可以将其覆盖或向其追加。 如果该文件不存在,此构造函数将创建一个新文件

♊ 属性AutoFlush 获取或设置一个值,该值指示 StreamWriter在每次调用 Write(Char) 之后是否都将其缓冲区刷新到基础流

♌ 常用方法Close() 关闭当前的 StreamWriter 和基础流Dispose() 释放由 WriteReader 对象使用的所有资源Flush() 清除此流的缓冲区,使得所有缓冲数据都写入到文件中FlushAsync() 异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中Write(Char[], Int32, Int32) 将字符的子数组写入文本流WriteAsync(Char[], Int32, Int32) 以异步形式将字符的子数组写入文本流WriteLine() 将行终止符写入文本流WriteLine(Char[], Int32, Int32) 将字符的子数组写入文本流,后跟行终止符Write(String)/Write(double)/Write(Int32)... 将`字符串、数值等`写入文本流WriteAsync(Char[], Int32, Int32) 将字符的子数组异步写入该流WriteLine(String)/WriteLine(double)/WriteLine(Int32)... 将`字符串、数值等`写入文本流,后跟行终止符WriteLineAsync(Char[], Int32, Int32) 将字符的子数组异步写入流,后跟行结束符

♎ 更多方法

1️⃣ System.IO命名空间

.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。

我们在.NET中的IO操作,经常需要调用一下几个类。

FileStream类

​ 文件流类,负责大文件的拷贝,读写。

Path类

​ Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。

File类 File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。 Dirctory类 目录操作,创建文件、删除目录,获取目录下文件名等等。

2️⃣ StreamWriter类

♈ 定义

实现一个 TextWriter,使其以一种特定的编码向流中写入字符。

public class StreamWriter : System.IO.TextWriter

示例

下面的示例演示如何使用 StreamWriter 对象写入一个文件,该文件列出 C 驱动器上的目录,然后使用 StreamReader 对象读取和显示每个目录名称。 一种很好的做法是在语句中使用这些对象, using 以便正确地释放非托管资源。 using当使用对象的代码已完成时,该语句会自动对 Dispose 该对象调用。 在此示例中使用的构造函数不支持在 Windows 应用商店应用程序中使用。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace StreamReadWrite

{

class Program

{

static void Main(string[] args)

{

// Get the directories currently on the C drive.

DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();

// Write each directory name to a file.

using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))

{

foreach (DirectoryInfo dir in cDirs)

{

sw.WriteLine(dir.Name);

}

}

// Read and show each line from the file.

string line = "";

using (StreamReader sr = new StreamReader("CDriveDirs.txt"))

{

while ((line = sr.ReadLine()) != null)

{

Console.WriteLine(line);

}

}

}

}

}

♉ 构造函数

StreamWriter(Stream) 初始化 StreamWriter类的新实例。

public StreamWriter (System.IO.Stream stream);

参数

stream

Stream

要写入的流。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

FileStream fs = null;

try

{

fs = new FileStream(fileName, FileMode.CreateNew);

using (StreamWriter writer = new StreamWriter(fs))

{

writer.Write(textToAdd);

}

}

finally

{

if (fs != null)

fs.Dispose();

}

}

}

}

StreamWriter(String) 使用指定的格式控件初始化 StreamWriter类的新实例

public StreamWriter (string path);

参数

path

String

要写入的完整文件路径。 path 可以是一个文件名。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

using (StreamWriter writer = new StreamWriter(fileName))

{

writer.Write(textToAdd);

}

}

}

}

StreamWriter(Stream, Encoding) 使用指定的编码及默认的缓冲区大小,为指定的流初始化 StreamWriter 类的新实例

public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding);

参数

stream

Stream

要写入的流。

encoding

Encoding

要使用的字符编码。

示例

下面的示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

FileStream fs = null;

try

{

fs = new FileStream(fileName, FileMode.CreateNew);

using (StreamWriter writer = new StreamWriter(fs, Encoding.Default))

{

writer.Write(textToAdd);

}

}

finally

{

if (fs != null)

fs.Dispose();

}

}

}

}

StreamWriter(String, Boolean) 用默认编码和缓冲区大小,为指定的文件初始化 StreamWriter 类的一个新实例。 如果该文件存在,则可以将其覆盖或向其追加。 如果该文件不存在,此构造函数将创建一个新文件

public StreamWriter (string path, bool append);

参数

path

String

要写入的完整文件路径。

append

Boolean

若要追加数据到该文件中,则为 true;若要覆盖该文件,则为 false。 如果指定的文件不存在,该参数无效,且构造函数将创建一个新文件。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

using (StreamWriter writer = new StreamWriter(fileName, true))

{

writer.Write(textToAdd);

}

}

}

}

StreamWriter(Stream, Encoding, Int32) 使用指定的编码及缓冲区大小,为指定的流初始化 StreamWriter 类的新实例

public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize);

参数

stream

Stream

要写入的流。

encoding

Encoding

要使用的字符编码。

bufferSize

Int32

缓冲区大小(以字节为单位)。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

FileStream fs = null;

try

{

fs = new FileStream(fileName, FileMode.CreateNew);

using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, 512))

{

writer.Write(textToAdd);

}

}

finally

{

if (fs != null)

fs.Dispose();

}

}

}

}

StreamWriter(String, Boolean, Encoding) 使用指定的编码和默认的缓冲区大小,为指定的文件初始化 StreamWriter 类的新实例。 如果该文件存在,则可以将其覆盖或向其追加。 如果该文件不存在,此构造函数将创建一个新文件

public StreamWriter (string path, bool append, System.Text.Encoding encoding);

参数

path

String

要写入的完整文件路径。

append

Boolean

若要追加数据到该文件中,则为 true;若要覆盖该文件,则为 false。 如果指定的文件不存在,该参数无效,且构造函数将创建一个新文件。

encoding

Encoding

要使用的字符编码。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.UTF8))

{

writer.Write(textToAdd);

}

}

}

}

StreamWriter(Stream, Encoding, Int32, Boolean) 使用指定的编码和缓冲区大小,为指定的流初始化 StreamWriter类的新实例,并可以选择保持流处于打开状态

public StreamWriter (System.IO.Stream stream, System.Text.Encoding? encoding = default, int bufferSize = -1, bool leaveOpen = false);

参数

stream

Stream

要写入的流。

encoding

Encoding

要使用的字符编码。

bufferSize

Int32

缓冲区大小(以字节为单位)。

leaveOpen

Boolean

如果在释放 StreamWriter 对象后保持流处于打开状态,则为 true;否则为 false。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

FileStream fs = null;

try

{

fs = new FileStream(fileName, FileMode.CreateNew);

using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, 512, false))

{

writer.Write(textToAdd);

}

}

finally

{

if (fs != null)

fs.Dispose();

}

}

}

}

StreamWriter(String, Boolean, Encoding, Int32) 使用指定编码和缓冲区大小,为指定路径上的指定文件初始化 StreamWriter类的新实例。 如果该文件存在,则可以将其覆盖或向其追加。 如果该文件不存在,此构造函数将创建一个新文件

public StreamWriter (string path, bool append, System.Text.Encoding encoding, int bufferSize);

参数

path

String

要写入的完整文件路径。

append

Boolean

若要追加数据到该文件中,则为 true;若要覆盖该文件,则为 false。 如果指定的文件不存在,该参数无效,且构造函数将创建一个新文件。

encoding

Encoding

要使用的字符编码。

bufferSize

Int32

缓冲区大小(以字节为单位)。

示例

下面的代码示例演示了此构造函数。

using System;

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program

{

static void Main(string[] args)

{

string fileName = "test.txt";

string textToAdd = "Example text in file";

using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.UTF8, 512))

{

writer.Write(textToAdd);

}

}

}

}

♊ 属性

AutoFlush 获取或设置一个值,该值指示 StreamWriter在每次调用 Write(Char) 之后是否都将其缓冲区刷新到基础流

public virtual bool AutoFlush { get; set; }

示例

// Gets or sets a value indicating whether the StreamWriter

// will flush its buffer to the underlying stream after every

// call to StreamWriter.Write.

sw.AutoFlush = true;

♌ 常用方法

Close() 关闭当前的 StreamWriter 和基础流

public override void Close ();

示例

此代码示例是为构造函数提供的大型示例的 StringWriter(StringBuilder) 一部分。

strWriter.Close();

// Since the StringWriter is closed, an exception will

// be thrown if the Write method is called. However,

// the StringBuilder can still manipulate the string.

strBuilder.Insert(0, "Invalid ");

Console.WriteLine(strWriter.ToString());

Dispose() 释放由 WriteReader 对象使用的所有资源

public void Dispose ();

Flush() 清除此流的缓冲区,使得所有缓冲数据都写入到文件中

public override void Flush ();

FlushAsync() 异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中

public override System.Threading.Tasks.Task FlushAsync ();

返回

Task

表示异步刷新操作的任务。

Write(Char[], Int32, Int32) 将字符的子数组写入文本流

public override void Write (char[] buffer, int index, int count);

参数

buffer

Char[]

要从中写出数据的字符数组。

index

Int32

在开始接收数据时缓存中的字符位置。

count

Int32

要写入的字符数。

示例

此示例从一个13元素数组向文件写入8个字符,从数组的第三个元素开始。

using System;

using System.IO;

public class SWBuff

{

public static void Main(String[] args)

{

FileStream sb = new FileStream("MyFile.txt", FileMode.OpenOrCreate);

char[] b = {'a','b','c','d','e','f','g','h','i','j','k','l','m'};

StreamWriter sw = new StreamWriter(sb);

sw.Write(b, 3, 8);

sw.Close();

}

}

WriteAsync(Char[], Int32, Int32) 以异步形式将字符的子数组写入文本流

public virtual System.Threading.Tasks.Task WriteAsync (char[] buffer, int index, int count);

参数

buffer

Char[]

要从中写出数据的字符数组。

index

Int32

在开始接收数据时缓存中的字符位置。

count

Int32

要写入的字符数。

返回

Task

表示异步写入操作的任务。

示例

下面的示例演示如何使用方法将多个字符写入文本文件 [WriteAsync(Char], Int32, Int32) 。

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program5

{

static void Main()

{

WriteCharacters();

}

static async void WriteCharacters()

{

UnicodeEncoding ue = new UnicodeEncoding();

char[] charsToAdd = ue.GetChars(ue.GetBytes("Example string"));

using (StreamWriter writer = File.CreateText("newfile.txt"))

{

await writer.WriteAsync(charsToAdd, 0, charsToAdd.Length);

}

}

}

}

WriteLine() 将行终止符写入文本流

public virtual void WriteLine ();

WriteLine(Char[], Int32, Int32) 将字符的子数组写入文本流,后跟行终止符

public virtual void WriteLine (char[] buffer, int index, int count);

参数

buffer

Char[]

要从中写出数据的字符数组。

index

Int32

在开始接收数据时缓存中的字符位置。

count

Int32

要写入的字符数。

Write(String)/Write(double)/Write(Int32)… 将字符串、数值等写入文本流

WriteAsync(Char[], Int32, Int32) 将字符的子数组异步写入该流

public override System.Threading.Tasks.Task WriteAsync (char[] buffer, int index, int count);

参数

buffer

Char[]

要从中写出数据的字符数组。

index

Int32

在开始接收数据时缓存中的字符位置。

count

Int32

要写入的字符数。

示例

下面的示例演示如何使用方法将多个字符写入文本文件 [WriteAsync(Char], Int32, Int32) 。

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program5

{

static void Main()

{

WriteCharacters();

}

static async void WriteCharacters()

{

UnicodeEncoding ue = new UnicodeEncoding();

char[] charsToAdd = ue.GetChars(ue.GetBytes("Example string"));

using (StreamWriter writer = File.CreateText("newfile.txt"))

{

await writer.WriteAsync(charsToAdd, 0, charsToAdd.Length);

}

}

}

}

WriteLine(String)/WriteLine(double)/WriteLine(Int32)… 将字符串、数值等写入文本流,后跟行终止符

WriteLineAsync(Char[], Int32, Int32) 将字符的子数组异步写入流,后跟行结束符

public override System.Threading.Tasks.Task WriteLineAsync (char[] buffer, int index, int count);

参数

buffer

Char[]

要从中写出数据的字符数组。

index

Int32

在开始接收数据时缓存中的字符位置。

count

Int32

要写入的字符数。

示例

下面的示例演示如何使用方法将字符写入文本文件中的两个单独的行 [WriteLineAsync(Char], Int32, Int32) 。 第一行包含字符串中的前11个字符, (字母 “First line” 后跟一个空格) 。 第二行包含字符串中的剩余字符 (字母 “和第二行” ) 。

using System.IO;

using System.Text;

namespace ConsoleApplication

{

class Program6

{

static void Main()

{

WriteCharacters();

}

static async void WriteCharacters()

{

UnicodeEncoding ue = new UnicodeEncoding();

char[] charsToAdd = ue.GetChars(ue.GetBytes("First line and second line"));

using (StreamWriter writer = File.CreateText("newfile.txt"))

{

await writer.WriteLineAsync(charsToAdd, 0, 11);

await writer.WriteLineAsync(charsToAdd, 11, charsToAdd.Length - 11);

}

}

}

}

♎ 更多方法

更多方法请查阅官方文档StreamWrite类。

⭐写在结尾:

文章中出现的任何错误请大家批评指出,一定及时修改。

希望写在这里的小伙伴能给个三连支持!

精彩文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: