我想读取一个文本文件并从其他文本文件中剪切单词,例如这是我的文本文件:
asd
asdc
asf
气体
asdf
现在我想读"asd",然后是"asdc",然后是"asf"…我怎么能做到呢?
使用StreamReader的ReadLine,您可以像这样逐行读取:
使用系统;使用先;
类测试{
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);
}
}
}
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);
}
此代码逐行读取文本文件,并将每行分隔成单词(通过空格和制表符)。你必须自己处理异常。