【.Net实用方法总结】 整理并总结System.IO中StreamWriter类及其方法介绍

简介: 本文主要介绍System.IO命名空间的StreamWriter类,介绍其常用的方法和示例说明。
🐋作者简介:博主是一位.Net开发者,同时也是RPA和低代码平台的践行者。
🐬个人主页: 会敲键盘的肘子
🐰系列专栏: .Net实用方法总结
🦀专栏简介:博主针对.Net开发和C站问答过程中遇到的问题进行总结,形成本专栏,希望可以帮助到您解决问题。
🐶座右铭:总有一天你所坚持的会反过来拥抱你。

🌈写在前面:

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


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

[TOC]

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< Int32>

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

示例

下面的示例演示如何使用方法将多个字符写入文本文件 WriteAsync(Char[], Int32, Int32)-system-int32-system-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)-system-int32-system-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)-system-int32-system-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类

⭐写在结尾:

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

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

相关文章
|
1月前
|
API 网络安全 数据安全/隐私保护
.NET邮箱API发送邮件的方法有哪些
本文介绍了.NET开发中使用邮箱API发送邮件的方法,包括SmtpClient类发送邮件、MailMessage类创建邮件消息、设置SmtpClient属性、同步/异步发送、错误处理、发送HTML格式邮件、带附件邮件以及多人邮件。AokSend提供高触达发信服务,适用于大规模验证码发送场景。了解这些技巧有助于开发者实现高效、可靠的邮件功能。
|
4月前
|
开发框架 .NET
ASP.NET Core NET7 增加session的方法
ASP.NET Core NET7 增加session的方法
38 0
|
5月前
|
存储 编解码 缓存
|
7月前
|
安全 网络协议 Java
Thread类的用法 && 线程安全 && 多线程代码案例 && 文件操作和 IO && 网络原理初识 &&UDP socket
Thread类的用法 && 线程安全 && 多线程代码案例 && 文件操作和 IO && 网络原理初识 &&UDP socket
40 0
|
23小时前
|
开发框架 .NET C语言
LabVIEW中使用.NET方法时出现错误1316
LabVIEW中使用.NET方法时出现错误1316
|
4月前
|
分布式计算 Java 大数据
IO流【Java对象的序列化和反序列化、File类在IO中的作用、装饰器模式构建IO流体系、Apache commons-io工具包的使用】(四)-全面详解(学习总结---从入门到深化)
IO流【Java对象的序列化和反序列化、File类在IO中的作用、装饰器模式构建IO流体系、Apache commons-io工具包的使用】(四)-全面详解(学习总结---从入门到深化)
54 0
|
9天前
|
存储 Java
Java的`java.io`包包含多种输入输出类
Java的`java.io`包包含多种输入输出类。此示例展示如何使用`FileInputStream`从`input.txt`读取数据。首先创建`FileInputStream`对象,接着分配一个`byte`数组存储流中的数据。通过`read()`方法读取数据,然后将字节数组转换为字符串打印。最后关闭输入流释放资源。`InputStream`是抽象类,此处使用其子类`FileInputStream`。其他子类如`ByteArrayInputStream`、`ObjectInputStream`和`BufferedInputStream`各有特定用途。
17 1
|
7月前
|
Windows
​史上最详细的Windows10系统离线安装.NET Framework 3.5的方法(附离线安装包下载)
​史上最详细的Windows10系统离线安装.NET Framework 3.5的方法(附离线安装包下载)
625 0
|
7月前
|
Java
已解决Java.net.MalformedURLException异常的有效方法java.net.MalformedURLException: no protocol异常处理
已解决Java.net.MalformedURLException异常的有效方法java.net.MalformedURLException: no protocol异常处理
373 0
|
3月前
|
运维 Java Unix
File类和IO流
File类和IO流
39 0