Windows系統(tǒng)中使用C#讀取文本文件內(nèi)容的小示例
讀取文本文件中的內(nèi)容
此示例讀取文本文件的內(nèi)容以使用 System.IO.File 選件類的靜態(tài)方法 ReadAllText 和 ReadAllLines。
class ReadFromFile
{
static void Main()
{
// The files used in this example are created in the topic
// How to: Write to a Text File. You can change the path and
// file name to substitute text files of your own.
// Example #1
// Read the file as one string.
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
// Display the file contents to the console. Variable text is a string.
System.Console.WriteLine("Contents of WriteText.txt = {0}", text);
// Example #2
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
// Display the file contents by using a foreach loop.
System.Console.WriteLine("Contents of WriteLines2.txt = ");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine("\t" + line);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
一次一行地讀取文本文件
本示例使用 StreamReader 類的 ReadLine 方法將文本文件的內(nèi)容讀?。ㄒ淮巫x取一行)到字符串中。所有文本行都保存在字符串 line 中并顯示在屏幕上。
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();
相關(guān)文章
C#數(shù)據(jù)結(jié)構(gòu)之隊(duì)列(Quene)實(shí)例詳解
這篇文章主要介紹了C#數(shù)據(jù)結(jié)構(gòu)之隊(duì)列(Quene),結(jié)合實(shí)例形式較為詳細(xì)的講述了隊(duì)列的功能、原理與C#實(shí)現(xiàn)隊(duì)列的相關(guān)技巧,需要的朋友可以參考下2015-11-11
C#實(shí)現(xiàn)窗體間傳遞數(shù)據(jù)實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)窗體間傳遞數(shù)據(jù)實(shí)例,需要的朋友可以參考下2014-07-07
C#模擬Http與Https請(qǐng)求框架類實(shí)例
這篇文章主要介紹了C#模擬Http與Https請(qǐng)求框架類,實(shí)例分析了處理http與https請(qǐng)求的方法與信息處理的技巧,需要的朋友可以參考下2014-12-12
C#實(shí)現(xiàn)Word轉(zhuǎn)換RTF的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)Word轉(zhuǎn)換RTF,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12
如何在C#項(xiàng)目中鏈接一個(gè)文件夾下的所有文件詳解
很多時(shí)候我們需要獲取一個(gè)結(jié)構(gòu)未知的文件夾下所有的文件或是指定類型的所有文件,下面這篇文章主要給大家介紹了關(guān)于如何在C#項(xiàng)目中鏈接一個(gè)文件夾下的所有文件,需要的朋友可以參考下2023-02-02

