如何检查文本文件中是否存在来自文本框的文本? [英] how do you check if text from a textbox is found in a text file?

查看:131
本文介绍了如何检查文本文件中是否存在来自文本框的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看在文本框中键入的文本是否包含在文本文件中.
因此,如果我要在文本框中键入"hello",我想知道文本文件中是否包含该单词,谢谢.

Hi, I want to see if text typed into a textbox is contained in a text file.
So if I were to type "hello" in the textbox I would like to know if the text file has that word, Thanks.

推荐答案

public bool checkForText(string filePath, string textBoxText)
{       
   using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
   {
       string[] linesToComapare = reader.ReadToEnd().Split('\n');
       for (int i = 0; i < linesToCompare.Count(); i++)
       {
          if (linesToCompare[i].Contains(textBoxText))
           {
               return true;
           }
       }
   }
      return false;
}


您可以使用 LiNQ [文本文件处理... [ ^ ]
使用linq逐字读取文本文件 [ ^ ]

如果您想读取分隔的文件:
使用LINQ读取分隔的文本文件 [ ^ ]
使用linq读取文本文件的教程 [如何:查询包含一组指定单词(LINQ)的句子 [ ^ ]
You can use LiNQ[^]!

Examples to find string in a text file:
Text file processing...[^]
read text file word by word using linq[^]

If you would like to read delimited files:
Using LINQ to read delimited text files[^]
tutorial reading a text file using linq[^]

And another example:
How to: Query for Sentences that Contain a Specified Set of Words (LINQ)[^]


解决方案2中 losmac 给出的引用很好.

如果只想检查文本文件中是否存在键入TextBox 的单词,那么我认为Regex 选项易于使用,如下所示
The references given by losmac in Solution 2 are good.

In case if you want to only check whether a word typed in the TextBox is present in the text file then I think the Regex option is simple to use as shown below
if (Regex.IsMatch(System.IO.File.ReadAllText(textFileName),
        string.Format(@"\s+{0}\s+",TextBox1.Text),
        RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))
            MessageBox.Show("Found");


如果要区分大小写,请删除上述语句中的| RegexOptions.IgnoreCase部分.


If you want to match case then remove | RegexOptions.IgnoreCase part in the above statement.


这篇关于如何检查文本文件中是否存在来自文本框的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆