C# 从磁盘中读取文件

it2026-09-27  10

读取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();

 

转载于:https://www.cnblogs.com/ZkbFighting/p/8215310.html

相关资源:数据结构—成绩单生成器
最新回复(0)