C# 中的文本阅读器

WBOY
发布: 2024-09-03 15:22:54
原创
1002 人浏览过

C# 中的 TextReader 用于从文本文件中读取文本或连续的字符序列。 TextReader 类位于 System.IO 命名空间下。它是StreamReader和StringReader的抽象基类,分别用于从流和字符串中读取字符。我们无法创建 TextReader 的对象,因为它是一个抽象类。默认情况下,TextReader 不是线程安全的。派生 TextReader 类的类需要至少实现 Peek() 和 Read() 方法才能创建有用的 TextReader 实例。

语法:

创建TextReader的语法如下:

TextReader text_reader = File.OpenText(file_path);
登录后复制
登录后复制

上述语句将在“file_path”指定的位置打开一个文件。然后,在 text_reader 的帮助下,我们可以使用 TextReader 类的方法来从文件中读取内容。

我们还可以借助“using”块创建 TextReader,如下所示:

using(TextReader text_reader = File.OpenText(file_path))
{
//user code
}
登录后复制

使用“using”块的优点是,当对象的工作完成并且不再需要该对象时,它会释放其中指定的对象获取的内存。

TextReader 在 C# 中如何工作?

为了使用 TextReader,有必要在我们的代码中导入 System.IO 命名空间。由于 TextReader 是一个抽象类,我们不能直接使用 new 关键字创建它的实例,但我们可以使用 File 类的 OpenText() 方法来实现,如下所示:

TextReader text_reader = File.OpenText(file_path);
登录后复制
登录后复制

OpenText() 方法将文件的位置作为输入,然后在同一位置打开现有的 UTF-8 编码文本文件进行读取。

File.OpenText() 方法返回 StreamReader 类的对象,该类是 TextReader 的派生类,因此有助于在代码中创建 TextReader 类的有用实例。该实例可用于调用 TextReader 类的方法来从文件中读取内容。 TextReader 类派生自抽象类 MarshalByRefObject。其继承层次如下所示:

对象 → MarshalByRefObject → TextReader

我们可以在 TextReader 的两个派生类(即 StreamReader 和 StringReader)的帮助下使用 TextReader。

  • StreamReader: 用于从特定编码的字节流中读取字符。
  • StringReader: 用于从字符串中读取文本。

TextReader的一些重要方法请参见下表:

Method Description
Close() It is used to close the TextReader and to release any system resources associated with it.
Dispose() It is used to release all the resources used by an object of TextReader.
Peek() It is used to read the next character without changing the state of the reader and it returns the next available character without actually reading it from the reader.
Read() It is used to read the next character from the text reader and it also advances the character position by one character.
ReadLine() It is used to read a line of characters from the text reader and it also returns the data as a string.
ReadToEnd() It is used to read all characters from the current position to the end of the text reader and it returns them as one string.
方法 说明 关闭() 它用于关闭 TextReader 并释放与其关联的任何系统资源。 Dispose() 用于释放TextReader对象使用的所有资源。 Peek() 它用于读取下一个字符而不改变读取器的状态,并返回下一个可用字符而不实际从读取器读取它。 读取() 用于从文本阅读器读取下一个字符,并将字符位置前进一个字符。 ReadLine() 它用于从文本阅读器读取一行字符,并以字符串形式返回数据。 ReadToEnd() 它用于读取从当前位置到文本阅读器末尾的所有字符,并将它们作为一个字符串返回。 表>

Examples of TextReader in C#

We can pass a text file name in a TextReader constructor to create an object. Following are the different examples of TextReader in C#.

Example #1

Reading a line of a file using the ReadLine() method of TextReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
try
{
if (File.Exists(file))
{
// opening the text file and reading a line
using (TextReader textReader = File.OpenText(file))
{
Console.WriteLine(textReader.ReadLine());
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
登录后复制

Output:

C# 中的文本阅读器

Example #2

Reading five characters from a file using the ReadBlock() method of TextReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
try
{
if (File.Exists(file))
{
//Opening the text file and reading 5 characters
using (TextReader textReader = File.OpenText(file))
{
char[] ch = new char[5];
textReader.ReadBlock(ch, 0, 5);
Console.WriteLine(ch);
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
登录后复制

Output:

C# 中的文本阅读器

Example #3

Reading the whole content of a text file using the ReadToEnd() method of TextReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
string content = String.Empty;
try
{
if (File.Exists(file))
{
//Opening a text file and reading the whole content
using (TextReader tr = File.OpenText(file))
{
content = tr.ReadToEnd();
Console.WriteLine(content);
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
登录后复制

Output:

C# 中的文本阅读器

Example #4

Reading the content of a text file using TextReader and writing it to another file.

Code:

using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string fileToRead = @"E:\Content\TextReader.txt";
string fileToWrite = @"E:\Content\TextReaderAndWriter.txt";
StringBuilder content = new StringBuilder();
string str = String.Empty;
try
{
//checking if the file exists to read
if (File.Exists(fileToRead))
{
//Opening a text file and reading the whole content
using (TextReader textReader = File.OpenText(fileToRead))
{
while ((str = textReader.ReadLine()) != null)
{
content.Append("\n" + str);
}
}
}
else
{
Console.WriteLine("File does not exist!");
}
//checking if the file to write content already exists
if (File.Exists(fileToWrite))
{
File.Delete(fileToWrite);
}
//creating file if it does not exist
using (TextWriter textWriter = File.CreateText(fileToWrite))
{
textWriter.WriteLine(content);
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
登录后复制

Output:

C# 中的文本阅读器

Conclusion

  • TextReader is an abstract class that is used to read text or sequential series of characters from a text file.
  • StreamReader and StringReader are two derived classes of TextReader with the help of which we can implement the methods of TextReader to read content from the text files.

以上是C# 中的文本阅读器的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!