在 c# 中,有几种有效地逐行读取文本文件的方法。
使用 c# 中的 file.readlines() 方法逐行读取文本文件
file.readlines()方法是高效地逐行读取文本文件的最佳方法。这个方法为大型文本文件返回一个枚举类型 enumerable,这就是为什么我们创建了一个 enumerable string 对象来存储文本文件的原因。
使用此方法的正确语法如下:
file.readlines(filename);
示例代码:
using system;
using system.collections.generic;
using system.io;
public class readfile
{
public static void main()
{
string filetoread = @"d:\new folder\textfile.txt";
// creating enumerable object
ienumerable<string> line = file.readlines(filetoread);
console.writeline(string.join(environment.newline, line));
}
}输出:
// all the text, the file contains will display here.
如果打开文件时出现问题,file.readlines() 方法将抛出 ioexception;如果请求的文件不存在,则抛出 filenotfoundexception。
使用 c# 中的file.readalllines() 方法逐行读取文本文件
file.readalllines()方法也可用于逐行读取文件。它不返回 enumerable。它返回一个字符串数组,其中包含文本文件的所有行。
使用此方法的正确语法如下:
file.readalllines(filename);
示例代码:
using system;
using system.io;
public class readfile
{
public static void main()
{
string filetoread = @"d:\new folder\textfile.txt";
// creating string array
string[] lines = file.readalllines(filetoread);
console.writeline(string.join(environment.newline, lines));
}
}输出:
// all the text, the file contains will display here.
这个方法也抛出异常,就像 file.readlines()方法一样。然后使用 try-catch 块来处理这些异常。
使用 c# 中的 streamreader.readline() 方法逐行读取文本文件
c# 中的 streamreader 类提供了 streamreader.readline() 方法。此方法逐行将文本文件读取到末尾。
streamreader.readline()方法的正确语法如下:
//we have to create streader object to use this method streamreader objectname = new streamreader(filename); objectname.readline();
示例代码:
using system;
using system.io;
public class readfile
{
public static void main()
{
string filetoread = @"d:\new folder\textfile.txt";
using (streamreader readerobject = new streamreader(filetoread))
{
string line;
// readerobject reads a single line, stores it in line string variable and then displays it on console
while((line = readerobject.readline()) != null)
{
console.writeline(line);
}
}
}
}输出:
// all the text, the file contains will display here.
到此这篇关于c#逐行读取文本文件的几种有效方法的文章就介绍到这了,更多相关c#读取文本文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论