C#逐行讀取文本文件的幾種有效方法
在 C# 中,有幾種有效地逐行讀取文本文件的方法。
使用 C# 中的 File.ReadLines() 方法逐行讀取文本文件
File.ReadLines()方法是高效地逐行讀取文本文件的最佳方法。這個方法為大型文本文件返回一個枚舉類型 Enumerable,這就是為什么我們創(chuàng)建了一個 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.
如果打開文件時出現(xiàn)問題,F(xiàn)ile.ReadLines() 方法將拋出 IOException;如果請求的文件不存在,則拋出 FileNotFoundException。
使用 C# 中的File.ReadAllLines() 方法逐行讀取文本文件
File.ReadAllLines()方法也可用于逐行讀取文件。它不返回 Enumerable。它返回一個字符串?dāng)?shù)組,其中包含文本文件的所有行。
使用此方法的正確語法如下:
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.
到此這篇關(guān)于C#逐行讀取文本文件的幾種有效方法的文章就介紹到這了,更多相關(guān)C#讀取文本文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
gridview的buttonfield獲取該行的索引值(實例講解)
本篇文章主要介紹了gridview的buttonfield獲取該行的索引值(實例講解)需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01
C# Winform按鈕中圖片實現(xiàn)左圖右字的效果實例
這篇文章主要給大家介紹了關(guān)于C# Winform按鈕中圖片實現(xiàn)左圖右字效果的相關(guān)資料,文中通過圖文介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

