博客
关于我
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中打散数组shuffle
查看>>
Python中执行外部命令
查看>>
Python中拼接numpy数组-ChatGPT4o作答
查看>>
Python中提示:no module named 'PIL'
查看>>
Python中提示:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position
查看>>
python中数据类型存储_浅谈Python中的数据类型
查看>>
python中文件最重要的功能是什么-学 Python 都用来干嘛的?
查看>>
python中文版语言_高盛最新调查:Python超过汉语成为未来最重要技能,你准备学哪种编程语言?...
查看>>
Python中文问题SyntaxError
查看>>
Python中方括号和括号括起来的列表有什么区别?
查看>>
python中时间处理_Python中处理时间的几种方法小结
查看>>
Python中枚举串口(包括虚拟端口)的跨平台方法是什么?
查看>>
python中根号下a怎么写_python中根号怎么表示
查看>>
Python中正则表达式的巧妙使用
查看>>
Python中浮点数的二进制表示(位不是十六进制)
查看>>
Python中特殊函数和表达式 filter,map,reduce,lambda
查看>>
python中用socket检测端口_Python 用socket模块实现检测端口和检测web服务
查看>>
python中用于列表操作的plus和append有什么区别?
查看>>
python中用递归求和
查看>>
python中的@staticmethod
查看>>