我正在尝试使用streamReader逐行读取文本文件。 我从文本框中获取文件路径,但它只读取最后一行
这是我在文本文件中替换stop关键字的代码。
try {
string line;
string path = textBox1.Text;
MessageBox.Show("Process is start");
//string text = System.IO.File.ReadAllText(richTextBox1.Text);
StreamReader file = new StreamReader(path);
MessageBox.Show(" process start reading file");
string[] stopWord = new string[] {
"is", "are", "am", "could", "will", "ing", "er", "est"
};
while ((line = file.ReadLine()) != null) {
// MessageBox.Show("in while");
FileStream fs1 = new FileStream(@
"D:\temp.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter file1 = new StreamWriter(fs1);
file1.WriteLine();
foreach(string word in stopWord) {
//line = line.Replace(word,Environment.NewLine);
line = line.Replace(word, "");
}
file1.WriteLine(line);
file1.Close();
}
/*Converting text file into binary */
file.Close();
}
答案 0 :(得分:1)
您还可以使用File
来简化此代码:
string text = File.ReadAllText(path);
foreach (var word in stopWords) text = text.Replace(word, "");
File.WriteAllText(@"D:\temp.txt", text);
它的可定制性要低得多,它会读取整个文件进行处理,这可能会导致性能问题 但是,如果您不打算使用大量数据,则可以使用此方法,因为它更短,更方便使用。
答案 1 :(得分:0)
使用:
string lines="";
FileStream fs1 = new FileStream(@
"D:\temp.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter file1 = new StreamWriter(fs1);
while ((line = file.ReadLine()) != null) {
// MessageBox.Show("in while");
file1.WriteLine();
foreach(string word in stopWord) {
//line = line.Replace(word,Environment.NewLine);
line = line.Replace(word, "");
}
lines +=line +Environment.Newline;
}
file1.WriteLine(lines);
file1.Close();
你在while循环中创建了新的file1,这就是它只显示最后一行的原因。用上面的代码替换你的while循环。