C#逐行讀取文本文件的幾種有效方法
在 C# 中,有幾種有效地逐行讀取文本文件的方法。
使用 C# 中的 File.ReadLines() 方法逐行讀取文本文件
File.ReadLines()方法是高效地逐行讀取文本文件的最佳方法。這個(gè)方法為大型文本文件返回一個(gè)枚舉類型 Enumerable,這就是為什么我們創(chuàng)建了一個(gè) Enumerable string 對(duì)象來(lái)存儲(chǔ)文本文件的原因。
使用此方法的正確語(yǔ)法如下:
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.
如果打開文件時(shí)出現(xiàn)問題,F(xiàn)ile.ReadLines() 方法將拋出 IOException;如果請(qǐng)求的文件不存在,則拋出 FileNotFoundException。
使用 C# 中的File.ReadAllLines() 方法逐行讀取文本文件
File.ReadAllLines()方法也可用于逐行讀取文件。它不返回 Enumerable。它返回一個(gè)字符串?dāng)?shù)組,其中包含文本文件的所有行。
使用此方法的正確語(yǔ)法如下:
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.
這個(gè)方法也拋出異常,就像 File.ReadLines()方法一樣。然后使用 try-catch 塊來(lái)處理這些異常。
使用 C# 中的 StreamReader.ReadLine() 方法逐行讀取文本文件
C# 中的 StreamReader 類提供了 StreamReader.ReadLine() 方法。此方法逐行將文本文件讀取到末尾。
StreamReader.ReadLine()方法的正確語(yǔ)法如下:
//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.
到此這篇關(guān)于C#逐行讀取文本文件的幾種有效方法的文章就介紹到這了,更多相關(guān)C#讀取文本文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
gridview的buttonfield獲取該行的索引值(實(shí)例講解)
本篇文章主要介紹了gridview的buttonfield獲取該行的索引值(實(shí)例講解)需要的朋友可以過來(lái)參考下,希望對(duì)大家有所幫助2014-01-01
C#使用Stack類進(jìn)行堆棧設(shè)計(jì)詳解
C#中的堆棧由System.Collections.Generic命名空間中的Stack類定義,那么下面就跟隨小編一起學(xué)習(xí)一下C#如何Stack類進(jìn)行堆棧設(shè)計(jì)吧2024-03-03
C# 如何使用 Index 和 Range 簡(jiǎn)化集合操作
這篇文章主要介紹了C# 如何使用 Index 和 Range 簡(jiǎn)化集合操作,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02
C# Winform按鈕中圖片實(shí)現(xiàn)左圖右字的效果實(shí)例
這篇文章主要給大家介紹了關(guān)于C# Winform按鈕中圖片實(shí)現(xiàn)左圖右字效果的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

