0
我想讀一個文本文件,並從對方砍的話,例如這是我的文本文件:如何讀取文本文件中的單詞在VC#
ASD
鼎新
ASF
氣
ASDF
現在我想讀「ASD」,然後在「鼎新」,然後在「ASF」 ...... 我怎麼能這樣做呢?
我想讀一個文本文件,並從對方砍的話,例如這是我的文本文件:如何讀取文本文件中的單詞在VC#
ASD
鼎新
ASF
氣
ASDF
現在我想讀「ASD」,然後在「鼎新」,然後在「ASF」 ...... 我怎麼能這樣做呢?
List<string> words = new List<string>();
string line;
char[] sep = new char[] { ' ', '\t' };
try
{
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null)
{
words.AddRange(line.Split(sep, StringSplitOptions.RemoveEmptyEntries));
}
file.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
該代碼讀取行文本文件中的行和每行分成字(由空間和製表符)。你必須自己處理例外情況。
使用StreamReader的ReadLine,您可以讀取這樣的行:
using System;使用System.IO的 ;
類測試 {
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
很抱歉,但我是新手,你能給我更多的幫助?
如何將它們打印在列表框中? –
您只需要將文件路徑替換爲'C:\\ test.txt',結果將作爲字符串列表包含在'words'變量中。 –