[英]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");
}
這是解決方案,其中比較文件中的整個單詞(由空格分隔)。
請檢查我作為代碼注釋所做的一些注釋(正確的錯誤處理,不區分大小寫的比較)。 我還將您的空字符串比較更正為更優雅。 此代碼段使用在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.