c# - 用于在文本文件中搜索确切字符串并在找到失败时执行操作的代码

标签 c# winforms visual-studio-2015

所以,我写了一些代码,假设读取一个文本文件,然后检查特定字符串的实例。如果该字符串存在,它将需要执行一个操作。我添加了一些消息框,让我知道功能的进度。问题是,它没有找到这个词。这是我的代码:

private void test2_Click(object sender, EventArgs e)
{
    StreamReader objReader = new StreamReader("C:\\testing\\mslogon.log");
    string sLine = "";
    ArrayList arrText = new ArrayList();
    MessageBox.Show("File Read");

    while (sLine != null)
    {
        sLine = objReader.ReadLine();
        if (sLine != null)
        {
            arrText.Add(sLine);
        }
    }

    if (arrText.Contains("Invalid"))
    {
        MessageBox.Show("Word Invalid Found");
    }
    else
    {
        MessageBox.Show("Nada");
    }
}

最佳答案

现在,您正在检查 arrText 中是否存在恰好等于“无效”的元素。如果“Invalid”嵌入到某个更大的字符串中,它将找不到它。

要检查是否有任何字符串包含 Invalid,您必须这样做:

foreach(var line in arrText)
{
    if (line.Contains("Invalid")) { MessageBox.Show("Word 'Invalid' Found"); break; }
}

使用@Alexei 提到的 File.ReadAllText 可以让你做一些你想做的事情,看起来像这样:

String wholeFile = File.ReadAllText();
if (wholeFile.Contains("Invalid")) { 
    MessageBox.Show("Word 'Invalid' Found"); 
} else {
. . .

关于c# - 用于在文本文件中搜索确切字符串并在找到失败时执行操作的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39044468/

相关文章:

c# - 如何在不同型号的 Controller 之间共享代码?

c# - 使用 IP 地址打印到网络打印机

visual-studio - Resharper 未检测到已安装 visual studio 2015

C++ - 当尝试在 TCP 客户端上连接到不存在的地址时,程序表现出奇怪的行为

c# - SignalR 如何接收自定义数据类型?

c# - 如何自动将从 FieldInfo.GetValue 获得的值转换为正确的类型?

c# - Linq to Xml 转换列表

c# - 克隆时如何复制自定义属性

c# - datagridview 中一个单元格中的多行

c# - 使用 .Netcore 库的 FxCop 分析在 VS2015 更新 3 中失败