簡體   English   中英

如何查看 TextBox.Text 是否是文本文件中的單詞之一

[英]How to see if a TextBox.Text is one of the words in text file

我想看看文本框文本是否是下載的 .txt 文件中的單詞之一。

我唯一知道的是,我可以使用if (words.Contains(txtBox.Text) ,但它會在文本文件中找到任何字母,並表現得像文件中的單詞一樣。

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string accessKeys;

            WebClient wc = new WebClient();
            accessKeys = wc.DownloadString("http://LinkToTextFile.txt");
            if (txtBxAccessKey.Text.Contains(" ") || txtBxAccessKey.Text == string.Empty)
            {
                MessageBox.Show("Empty");
            }
            else if (accessKeys.Contains(txtBxAccessKey.Text)) //This is what I need to change to work as intended
            {
                this.Hide();
                Loader frmLoader = new Loader();
                frmLoader.ShowDialog();
            }
            else
            {
                MessageBox.Show("Access Key Not Found");
            }

這是解決方案,其中比較文件中的整個單詞(由空格分隔)。

  1. 將文件數據下載為字符串
  2. 將字符串拆分為字符串數組,由任何空格(空格、換行符、制表符)分隔
  3. 檢查 txtBxAccessKey.Text 是否是數組項之一

請檢查我作為代碼注釋所做的一些注釋(正確的錯誤處理,不區分大小寫的比較)。 我還將您的空字符串比較更正為更優雅。 此代碼段使用在System.Linq命名空間中找到的Contains方法。

using System.Linq;

private void btnLogin_Click(object sender, EventArgs e)
{
    WebClient wc = new WebClient();
    var fileContents = wc.DownloadString("http://LinkToTextFile.txt");
    //Todo 1: Error handling, check for empty!
    //Todo 2: Handle case in-sensitive comparison!
    string[] lines = fileContents.Split(null);

    if (string.IsNullOrEmpty(txtBxAccessKey.Text))
    {
        MessageBox.Show("Empty");
        return;
    }
    else if (lines.Contains(txtBxAccessKey.Text))
    {
        this.Hide();
        Loader frmLoader = new Loader();
        frmLoader.ShowDialog();
    }
    else
    {
        MessageBox.Show("Access Key Not Found");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM