-6

例如:如果文本文件有苹果 -Messagebox.Show("This word is exist");

别的

Messagebox.Show("The word does not exist!");
如果文本文件中没有这些单词将被自动保存并且自动为文本文件中不存在的单词创建一个新行。

4

2 回答 2

1

单程:

要读取文件,您必须TextReader在 C# 中使用 a:

TextReader reader = File.OpenText(@"YOUR PATH HERE");

创建TextReader-object 后,您可以通过以下方式读取文件的整个文本:

    string text = reader.ReadToEnd();

阅读文件后,您可以关闭TextReader

reader.Close();

另一种方式(否TextReader

您可以使用File.ReadAllText(@"YOUR PATH HERE");

string text = File.ReadAllText(@"YOUR PATH HERE");

要在 astring或 text 中搜索特定单词,请使用string.Contains("your word here");

这将返回bool字符串是否包含单词:

bool contains = string.Contains("your word here");
  • contains = true -> 单词在文本中。
  • contains = false -> 单词不在文本中。

基于 的值contains,您现在可以显示MessageBox

我总是建议using在您使用 Stream- 或 TextReaders/Writers 时使用它,这样您就不必处理处理和刷新/关闭读取器/写入器:

using(TextReader reader = File.OpenText(@"YOUR PATH HERE")){
     string text = reader.ReadToEnd();
} //No closing needed here (close will automatically be called, when the object gets disposed
于 2013-08-22T06:37:45.543 回答
0

阅读所有文本

  string fileText = File.ReadAllText("filePath");
  if (fileText.Contains("apple"))
  {
       Messagebox.Show("This word is exist");
  }
  else
  {
       Messagebox.Show("The word does not exist!");
       File.AppendAllText(@"filePAth", "The word does not exixt in the text file" + Environment.NewLine);
  }
于 2013-08-22T06:39:54.570 回答