博客
关于我
C#开发之——StreamReader(10.8)
阅读量:98 次
发布时间:2019-02-26

本文共 1271 字,大约阅读时间需要 4 分钟。

C# StreamReader类详解
StreamReader类是C#中用于读取流数据的重要工具,本文将详细介绍其使用方法和实例操作。

一、概述

StreamReader类似于FileStream类,可用于从文件或流中读取文本数据。该类继承自TextReader类,支持多种编码方式,能够以不同方式读取文件内容。

二、构造方法

StreamReader类提供多种构造方式,用户可根据需求选择合适的方法创建实例:

1. 基于流创建实例

StreamReader(Stream stream) - 根据指定流创建StreamReader实例。

2. 基于文件路径创建实例

StreamReader(string path) - 根据指定文件路径创建StreamReader实例。

3. 带编码参数创建实例

StreamReader(Stream stream, Encoding encoding) - 根据指定流和编码方式创建StreamReader实例。
StreamReader(string path, Encoding encoding) - 根据指定文件路径和编码方式创建StreamReader实例。
  • 通过上述构造方法即可创建StreamReader实例,随后可通过类成员方法进行文件读取操作。

三、常用属性和方法

StreamReader类提供丰富的属性和方法,主要包括:
属性/方法 作用
CurrentEncoding 获取当前流使用的编码方式
EndOfStream 判断当前流位置是否已达到结尾
Close() 关闭当前流
Peek() 获取下一个字符的整数值
Read() 读取单个字符
Read(char[] buffer, int index, int count) 读取指定长度的字符到缓冲区
ReadLine() 读取一行文本
ReadToEnd() 读取流结尾至当前位置的所有字符

四、实例:读取D盘directoryInfo文件夹下test1.txt文件中的信息

代码示例

class Program{    static void Main(string[] args)    {        string path = @"D:\directoryInfo\test1.txt";        StreamReader streamReader = new StreamReader(path);        while (streamReader.Peek() != -1)        {            string str = streamReader.ReadLine();            Console.WriteLine(str);        }        streamReader.Close();    }}

说明

除了ReadLine方法外,还可以使用Read、ReadToEnd等方法读取文件内容。通过合理组合这些方法,可实现对文件内容的不同读取方式。

转载地址:http://nsik.baihongyu.com/

你可能感兴趣的文章
python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
查看>>
Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
查看>>
Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
查看>>
Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
查看>>
python出现 unknown encoding: idna 的处理方法
查看>>
Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
查看>>
Python-numpy(2)数组的操作
查看>>
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>