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

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

一 概述

C#语言中StreamReader类似于从流中读取字符串。它继承自TextReader类

二 构造方法

2.1 构造方法

构造方法 说明
StreamReader(Stream stream) 为指定的流创建 StreamReader 类的实例
StreamReader(string path) 为指定路径的文件创建 StreamReader 类的实例
StreamReader(Stream stream, Encoding encoding) 用指定的字符编码为指定的流初始化 StreamReader 类的一个新实例
StreamReader(string path, Encoding encoding) 用指定的字符编码为指定的文件名初始化 StreamReader 类的一个新实例
  • 使用该表中的构造方法即可创建StreamReader类的实例,通过实例调用其提供的类成员能进行文件的读取操作

三 常用属性和方法

属性或方法 作用
Encoding CurrentEncoding 只读属性,获取当前流中使用的编码方式
bool EndOfStream 只读属性,获取当前的流位置是否在流结尾
void Close() 关闭流
int Peek() 获取流中的下一个字符的整数,如果没有获取到字符, 则返回 -1
int Read() 获取流中的下一个字符的整数
int Read(char[] buffer, int index, int count) 从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区
string ReadLine() 从当前流中读取一行字符并将数据作为字符串返回
string ReadToEnd() 读取来自流的当前位置到结尾的所有字符

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

4.1 代码

复制
123456789101112131415161718
class Program{    static void Main(string[] args)    {        //定义文件路径        string path = @"D:\\directoryInfo\\test1.txt";        //创建 StreamReader 类的实例        StreamReader streamReader = new StreamReader(path);        //判断文件中是否有字符        while (streamReader.Peek() != -1)        {            //读取文件中的一行字符            string str = streamReader.ReadLine();            Console.WriteLine(str);        }        streamReader.Close();    }}

4.2 说明

在读取文件中的信息时,除了可以使用ReadLine方法之外,还可以使用Read、ReadToEnd方法来读取

 

 

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

你可能感兴趣的文章
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>