用于从流中读取数据并将数据转换为字符的 C# 程序
给定数据,现在我们的任务是从流中读取数据并将数据转换为 C# 中的字符。因此,为了完成这项任务,我们使用以下类和方法:
- FileStream :它是一个用于读取和写入文件的类。因此,要使用 FileStream 操作文件,您需要创建 FileStream 类的对象。
语法:
Stream object = new FileStream(path, FileMode.Open)
其中path是您的文件的位置 - @”c:\A\data.txt” 和 FileMode 是文件的模式,如读取和写入。
- ReadByte():该方法用于逐字节从文件中读取数据。当前流不支持读取时,该方法会抛出 NotSupportException。如果当前流已关闭,则此方法将抛出 ObjectDisposedException。
句法:
FileStream_object.ReadByte()
示例:
让我们考虑一个名为“file.txt”的文件存在于 C 盘的 A 文件夹中,如下图所示:
现在我们从流中读取数据并将数据转换为字符。因此,请遵循以下方法。
方法
- Read the file named “file.txt” using FileStream with the help of specified path.
- Read the data in file byte by byte using ReadByte() method until it reaches end of file.
- Display file data into chars using Casting to char.
C#
while ((obj = s.ReadByte()) != -1)
{
// Convert the data into chars and display
Console.Write("{0} ", (char)obj);
}
输出:
(char)obj