当前位置: 代码网 > it编程>编程语言>Asp.net > C#逐行读取文本文件的几种有效方法

C#逐行读取文本文件的几种有效方法

2025年01月15日 Asp.net 我要评论
在 c# 中,有几种有效地逐行读取文本文件的方法。使用 c# 中的 file.readlines() 方法逐行读取文本文件file.readlines()方法是高效地逐行读取文本文件的最佳方法。这个方

在 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#读取文本文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com