码迷,mamicode.com
首页 > Windows程序 > 详细

C# 从磁盘中读取文件

时间:2018-01-06 22:14:29      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:代码   读取内容   files   获取   分享   none   console   .net   span   

读取txt文件

------读取的数据比较小的时候:

如果你要读取的文件内容不是很多,可以使用 File.ReadAllText(filePath) 或指定编码方式 File.ReadAllText(FilePath, Encoding)的方法。它们都一次性将文本内容全部读完,并返回一个包含全部文本内容的字符串

用string接收

string str1 = File.ReadAllText(@"c:\temp\a.txt"); //也可以指定编码方式
string str2 = File.ReadAllText(@"c:\temp\a.txt", Encoding.ASCII);

也可以使用方法File.ReadAllLines,该方法一次性读取文本内容的所有行,返回一个字符串数组,数组元素是每一行的内容

string[] strs1 = File.ReadAllLines(@"c:\temp\a.txt"); 
// 也可以指定编码方式 
string[] strs2 = File.ReadAllLines(@"c:\temp\a.txt", Encoding.ASCII); 

-----读取数据比较大的时候,采用流的方式:

当文本的内容比较大时,我们就不要将文本内容一次性读完,而应该采用流(Stream)的方式来读取内容。

  .Net为我们封装了StreamReader类,它旨在以一种特定的编码从字节流中读取字符。StreamReader类的方法不是静态方法,所以要使用该类读取文件首先要实例化该类,在实例化时,要提供读取文件的路径。

StreamReader sR1 = new StreamReader(@"c:\temp\a.txt");

// 读一行

string nextLine = sR.ReadLine();
// 同样也可以指定编码方式
StreamReader sR2 = new StreamReader(@"c:\temp\a.txt", Encoding.UTF8);

FileStream fS = new FileStream(@"C:\temp\a.txt", FileMode.Open, FileAccess.Read, FileShare.None);
StreamReader sR3 = new StreamReader(fS);
StreamReader sR4 = new StreamReader(fS, Encoding.UTF8);

FileInfo myFile = new FileInfo(@"C:\temp\a.txt");
// OpenText 创建一个UTF-8 编码的StreamReader对象
StreamReader sR5 = myFile.OpenText();
// OpenText 创建一个UTF-8 编码的StreamReader对象
StreamReader sR6 = File.OpenText(@"C:\temp\a.txt");

获取到大的文件后,都是流的返回形式

可以用流的读取方法读出数据,返回类型是String类型

// 读一行
string nextLine = sR.ReadLine();
// 读一个字符
int nextChar = sR.Read();
// 读100个字符
int n = 100; char[] charArray = new char[n]; int nCharsRead = sR.Read(charArray, 0, n);
// 全部读完
string restOfStream = sR.ReadToEnd();

使用完StreamReader之后,不要忘记关闭它: sR.Close();

  假如我们需要一行一行的读,将整个文本文件读完,下面看一个完整的例子:

技术分享图片
StreamReader sR = File.OpenText(@"C:\temp\a.txt"); 
string nextLine; 
while ((nextLine = sR.ReadLine()) != null) 
{ 
    Console.WriteLine(nextLine); 
} 
sR.Close(); 
技术分享图片

 

C# 从磁盘中读取文件

标签:代码   读取内容   files   获取   分享   none   console   .net   span   

原文地址:https://www.cnblogs.com/ZkbFighting/p/8215310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!