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

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

🌈写在前面:

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


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

[TOC]

1️⃣ System.IO命名空间

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

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

  • FileStream类

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

  • Path类

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

  • File类

    File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。

  • Dirctory类

    目录操作,创建文件、删除目录,获取目录下文件名等等。

2️⃣ StringWriter类

♈ 定义

实现用于将信息写入字符串的 TextWriter。 信息存储在基础 StringBuilder 中。

public class StringWriter : System.IO.TextWriter

示例

下面的代码示例演示如何从一组双空格句子创建连续段落,然后将段落转换回原始文本。

using System;
using System.IO;

class StringRW
{
    static void Main()
    {
        string textReaderText = "TextReader is the abstract base " +
            "class of StreamReader and StringReader, which read " +
            "characters from streams and strings, respectively.\n\n" +

            "Create an instance of TextReader to open a text file " +
            "for reading a specified range of characters, or to " +
            "create a reader based on an existing stream.\n\n" +

            "You can also use an instance of TextReader to read " +
            "text from a custom backing store using the same " +
            "APIs you would use for a string or a stream.\n\n";

        Console.WriteLine("Original text:\n\n{0}", textReaderText);

        // From textReaderText, create a continuous paragraph
        // with two spaces between each sentence.
        string aLine, aParagraph = null;
        StringReader strReader = new StringReader(textReaderText);
        while(true)
        {
            aLine = strReader.ReadLine();
            if(aLine != null)
            {
                aParagraph = aParagraph + aLine + " ";
            }
            else
            {
                aParagraph = aParagraph + "\n";
                break;
            }
        }
        Console.WriteLine("Modified text:\n\n{0}", aParagraph);

        // Re-create textReaderText from aParagraph.
        int intCharacter;
        char convertedCharacter;
        StringWriter strWriter = new StringWriter();
        strReader = new StringReader(aParagraph);
        while(true)
        {
            intCharacter = strReader.Read();

            // Check for the end of the string
            // before converting to a character.
            if(intCharacter == -1) break;

            convertedCharacter = (char)intCharacter;
            if(convertedCharacter == '.')
            {
                strWriter.Write(".\n\n");

                // Bypass the spaces between sentences.
                strReader.Read();
                strReader.Read();
            }
            else
            {
                strWriter.Write(convertedCharacter);
            }
        }
        Console.WriteLine("\nOriginal text:\n\n{0}",
            strWriter.ToString());
    }
}
StringReader 使你可以同步或异步读取字符串。 可以使用或 ReadAsync方法一次读取字符、一次 Read使用 ReadLine或方法的行以及使用 ReadToEndReadLineAsync ReadToEndAsync方法的整个字符串。

♉ 构造函数

StringWriter() 初始化 StringWriter类的新实例。
public StringWriter ();

示例

下面的代码示例演示如何使用 StringWriter 类构造字符串。

using System;
using System.IO;
using System.Text;

class StrWriter
{
    static void Main()
    {
        StringWriter strWriter  = new StringWriter();

        // Use the three overloads of the Write method that are
        // overridden by the StringWriter class.
        strWriter.Write("file path characters are: ");
        strWriter.Write(
            Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);
        strWriter.Write('.');

        // Use the underlying StringBuilder for more complex
        // manipulations of the string.
        strWriter.GetStringBuilder().Insert(0, "Invalid ");

        Console.WriteLine("The following string is {0} encoded.\n{1}",
            strWriter.Encoding.EncodingName, strWriter.ToString());
    }
}
StringWriter(IFormatProvider) 使用指定的格式控件初始化 StringWriter类的新实例
public StringWriter (IFormatProvider? formatProvider);

参数

formatProvider

IFormatProvider

控制格式设置的 IFormatProvider 对象。

示例

下面的代码示例演示如何在特定区域性中构造字符串。

using System;
using System.Globalization;
using System.IO;

class StrWriter
{
    static void Main()
    {
        StringWriter strWriter =
            new StringWriter(new CultureInfo("ar-DZ"));

        strWriter.Write(DateTime.Now);

        Console.WriteLine(
            "Current date and time using the invariant culture: {0}\n" +
            "Current date and time using the Algerian culture: {1}",
            DateTime.Now.ToString(), strWriter.ToString());
    }
}
StringWriter(StringBuilder) 初始化写入到指定的 StringBuilder 中的 StringWriter 类的新实例
public StringWriter (System.Text.StringBuilder sb);

参数

sb

StringBuilder

要写入的 StringBuilder 对象。

示例

下面的代码示例演示如何使用 StringBuilder 类修改已关闭 StringWriter的基础字符串。

using System;
using System.IO;
using System.Text;

class StrWriter
{
    static void Main()
    {
        StringBuilder strBuilder =
            new StringBuilder("file path characters are: ");
        StringWriter strWriter = new StringWriter(strBuilder);

        strWriter.Write(
            Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);

        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());
    }
}

♌ 常用方法

Close() 关闭当前的 StringWriter 和基础流
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 virtual 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

要写入的字符数。

此方法将从count位置开始的buffer字符数组将数据写入此TextWriter`index`字符。

此重载等效于Write(Char[])))介于index和 () index`count + 中的每个字符buffer`的重载。

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>

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

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)... 将字符串、数值等写入文本流
WriteLine(String)/WriteLine(double)/WriteLine(Int32)... 将字符串、数值等写入文本流,后跟行终止符
Write(String, Object) 使用与 Format(String, Object)方法相同的语义将格式化字符串写入文本流
public virtual void Write (string format, object? arg0);

示例

设置单个参数的格式

下面的示例使用 方法将个人的年龄嵌入 Format(String, Object)) 字符串的中间。

DateTime birthdate = new DateTime(1993, 7, 28);
DateTime[] dates = { new DateTime(1993, 8, 16), 
                     new DateTime(1994, 7, 28), 
                     new DateTime(2000, 10, 16), 
                     new DateTime(2003, 7, 27), 
                     new DateTime(2007, 5, 27) };

foreach (DateTime dateValue in dates)
{
   TimeSpan interval = dateValue - birthdate;
   // Get the approximate number of years, without accounting for leap years.
   int years = ((int) interval.TotalDays) / 365;
   // See if adding the number of years exceeds dateValue.
   string output;
   if (birthdate.AddYears(years) <= dateValue) {
      output = String.Format("You are now {0} years old.", years);
      Console.WriteLine(output);
   }   
   else {
      output = String.Format("You are now {0} years old.", years - 1);
      Console.WriteLine(output);
   }      
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.

♎ 更多方法

更多方法请查阅官方文档 StringWrite类

⭐写在结尾:

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

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

相关文章
|
30天前
|
SQL 缓存 开发框架
分享一个 .NET EF6 应用二级缓存提高性能的方法
分享一个 .NET EF6 应用二级缓存提高性能的方法
|
29天前
|
Java
IO流操作-------File类、输入流和输出流(二)
这篇文章介绍了Java中IO流操作的基本概念和使用,包括字节流和字符流的读取与写入,以及如何使用缓冲流提高文件读写效率和实现文件复制的方法。
IO流操作-------File类、输入流和输出流(二)
|
29天前
|
Java
IO流操作-------File类(一)
这篇文章介绍了Java中File类的常用操作,包括创建文件/文件夹、删除文件、查询文件属性(如存在性、大小、名称、路径)以及递归遍历文件夹下所有文件的方法。
IO流操作-------File类(一)
|
30天前
|
缓存 程序员
封装一个给 .NET Framework 用的内存缓存帮助类
封装一个给 .NET Framework 用的内存缓存帮助类
|
1月前
|
存储 缓存 Java
15 Java IO流(File类+IO流+字节流+字符流+字节编码)
15 Java IO流(File类+IO流+字节流+字符流+字节编码)
40 3
|
30天前
|
程序员 数据库
分享 2 个 .NET EF 6 只更新某些字段的方法
分享 2 个 .NET EF 6 只更新某些字段的方法
|
30天前
|
数据库
分享一个 .NET EF 6 扩展 Where 的方法
分享一个 .NET EF 6 扩展 Where 的方法
|
30天前
|
开发框架 前端开发 算法
分享 .NET EF6 查询并返回树形结构数据的 2 个思路和具体实现方法
分享 .NET EF6 查询并返回树形结构数据的 2 个思路和具体实现方法
|
30天前
|
开发框架 中间件 .NET
分享 ASP.NET Core Web Api 中间件获取 Request Body 两个方法
分享 ASP.NET Core Web Api 中间件获取 Request Body 两个方法
|
30天前
|
开发框架 .NET API
如何在 ASP.NET Core Web API 方法执行前后 “偷偷“ 作一些 “坏“ 事?初识 ActionFilterAttribute
如何在 ASP.NET Core Web API 方法执行前后 “偷偷“ 作一些 “坏“ 事?初识 ActionFilterAttribute