博客
关于我
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/

你可能感兴趣的文章
PIL.Image进行图像融合显示(Image.blend)
查看>>
pilicat-dfs 霹雳猫-分布式文件系统
查看>>
Pillow lacks the JPEG 2000 plugin
查看>>
SpringBoot之ElasticsearchRestTemplate常用示例
查看>>
ping 全网段CMD命令
查看>>
ping 命令的七种用法,看完瞬间成大神
查看>>
Pinia入门(快速上手)
查看>>
Pinia:$patch的使用场景
查看>>
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install mysqlclient报错
查看>>
pip install 出现报asciii码错误的解决
查看>>
pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
查看>>
pip 下载慢
查看>>
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>