逐行读取远程文本文件并与输入框条目进行比较

时间:2015-06-13 00:19:39

标签: c# file

我用输入框编写了一个应用程序,我希望人们输入密码,这些密码将从文本文件中存储在我的网络服务器中的密码列表进行比较,这些密码是每行中的一个条目,然后可以访问我的应用程序

所以简单地说,我希望将输入框密码逐行比较到我的文本文件,但到目前为止我没有这样做

这是我的代码:

string input = 
    Microsoft.VisualBasic.Interaction.InputBox("Please enter your password for access to this software", "pass:");

if (input=="")
{
    appexit();
}

WebClient client = new WebClient();
Stream stream = client.OpenRead("http://haha.com/access.txt");
StreamReader reader = new StreamReader(stream);
//String content = reader.ReadToEnd();

int counter = 0;
string line;

while ((line = reader.ReadLine()) != null)
{
    if (line!=input)
    {
        MessageBox.Show("This software has been deactivated because of wrong pass", "YOUR ACCESS HAS BEEN LIMITED");
        appexit();
    }

    counter++;
}

reader.Close();

密码文件包含以下行:

hahdfdsf 
ha22334rdf 
ha2233gg 
charlysv-es

错误在哪里?代码编译但即使输入了正确的密码,检查也会失败。

1 个答案:

答案 0 :(得分:2)

根据你的循环,一旦你获得了不等于输入的行,那么你就会停止一切 - 逻辑错误。 您必须比较行,直到其中一行等于输入或文件结尾。

 ...
 bool valid = false;

 using (WebClient client = new WebClient())
 {
     using (Stream stream = client.OpenRead("http://haha.com/access.txt"))
     {
         using (StreamReader reader = new StreamReader(stream))
         {
             string line;

             while ((line = reader.ReadLine()) != null)
             {
                 if (line.Equals(input))
                 {
                     valid = true;
                     break;
                 }
             }
         }
     }
 }

 if (valid)
 {
     // password is correct
     ...
 }
 else
 {
    MessageBox.Show("This software has been deactivated because of wrong pass", "YOUR ACCESS HAS BEEN LIMITED");
    appexit();
 }
 ...