简体   繁体   English

如何使用C#检查文本框是否有TXT文件中的一行

[英]How to check if a textbox has a line from a TXT File with C#

It's simple what I'm trying to do; 我想做的很简单; when I click a button, my app should check if textBox1.Text has a line from a text file. 当我单击按钮时,我的应用程序应检查textBox1.Text是否有文本文件中的一行。

Note: I don't want to check if textbox has all the text file in it, just to see if it has a LINE from it. 注意:我不想检查文本框是否包含所有文本文件,只是想看看它是否有LINE。

I tried this with no success: 我尝试了一下但没有成功:

 private void acceptBtn_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(usersPath);
        string usersTXT = sr.ReadLine();
        if (user_txt.Text == usersTXT)
        {
            loginPanel.Visible = false;
        }
    }

Hope someone can help me. 希望可以有人帮帮我。 Thanks in Advance - CCB 在此先感谢-CCB

string usersTXT = sr.ReadLine();

Reads exactly one line. 仅读取一行。 So you are only checking if you match the first line in the file. 因此,您仅检查文件中的第一行是否匹配。

You want File.ReadALlLines (which also disposes the stream correctly, which you aren't): 您需要File.ReadALlLines (它也可以正确处理流,但实际上不是):

if (File.ReadAllLines(usersPath).Contains(user_txt.Text))
{
}

That reads all the lines, enumerates them all checking if your line is in the collection. 读取所有行,枚举它们,检查您的行是否在集合中。 The only downside to this approach is that it always reads the entire file. 这种方法的唯一缺点是,它始终读取整个文件。 If you want to only read until you find your input, you'll need to roll the read loop yourself. 如果您只想阅读直到找到输入,则需要自己滚动读取循环。 Do make sure to use the StreamReader in a using block if you take that route. 如果采用该路由,请确保在using块中使用StreamReader

You can also just use File.ReadLines (thanks @Selman22) to get the lazy enumeration version of this. 您也可以只使用File.ReadLines (感谢@ Selman22)来获取此的惰性枚举版本。 I would go with this route personally. 我个人会选择这条路线。

Implemenation that shows this at: http://referencesource.microsoft.com/#mscorlib/system/io/file.cs,675b2259e8706c26 在以下网址显示的实现: http : //referencesource.microsoft.com/#mscorlib/system/io/file.cs,675b2259e8706c26

if (File.ReadAllLines(path).Any(x => x == line))
{
    // line found
}

Replace x == line with a case-insensitive check or Contains if you want. 用不区分大小写的检查替换x == line ,或者根据需要替换为Contains

Try using the Contains() function on the string: 尝试在字符串上使用Contains()函数:

private void acceptBtn_Click(object sender, EventArgs e)
{
    StreamReader sr = new StreamReader(usersPath);
    string usersTXT = sr.ReadLine();
    if (user_txt.Text.Contains(usersTXT))
    {
        loginPanel.Visible = false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM