作者简介:博主是一位.Net开发者,同时也是RPA和低代码平台的践行者。
个人主页:会敲键盘的肘子
系列专栏:.Net实用方法总结
专栏简介:博主针对.Net开发和C站问答过程中遇到的问题进行总结,形成本专栏,希望可以帮助到您解决问题。
座右铭:总有一天你所坚持的会反过来拥抱你。
写在前面:
本文主要介绍System.IO命名空间的StringWriter 类,介绍其常用的方法和示例说明。
本文关键字:System.IO、StringWriter类、方法示例、C#
.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
我们在.NET中的IO操作,经常需要调用一下几个类。
文件流类,负责大文件的拷贝,读写。
Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。
File类
File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。
Dirctory类
目录操作,创建文件、删除目录,获取目录下文件名等等。
实现用于将信息写入字符串的 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或方法的行以及使用ReadToEnd或ReadLineAsyncReadToEndAsync方法的整个字符串。
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());
}
}
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());
}
}
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());
}
}
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());
public void Dispose ();
public virtual void Flush ();
public override System.Threading.Tasks.Task FlushAsync ();
返回
Task
表示异步刷新操作的任务。
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
的重载。
public virtual System.Threading.Tasks.Task WriteAsync (char[] buffer, int index, int count);
参数
buffer
Char[]
要从中写出数据的字符数组。
index
Int32
在开始接收数据时缓存中的字符位置。
count
Int32
要写入的字符数。
返回
Task
表示异步写入操作的任务。
public virtual void WriteLine ();
public virtual void WriteLine (char[] buffer, int index, int count);
参数
buffer
Char[]
要从中写出数据的字符数组。
index
Int32
在开始接收数据时缓存中的字符位置。
count
Int32
要写入的字符数。
字符串、数值等
写入文本流字符串、数值等
写入文本流,后跟行终止符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类。
⭐写在结尾:
文章中出现的任何错误请大家批评指出,一定及时修改。
希望写在这里的小伙伴能给个三连支持!