2011-08-24 74 views
0

我在文件中存储的是与帐户相关的值。 (只是测试,不会被商业使用)。我需要的是通过遍历每一个新行来绘制用户名和密码的值,但.peek()似乎不适用于我。我究竟做错了什么?我的块看起来像这样:使用StreamReader从文本文件中读取新行

 public string CheckAccount(string username, string password) 
    { 
     StreamReader sr; 
     string filename = "H:\\AccountInfo.txt"; 
     string s; 
     string result = ""; 
     sr = File.OpenText(filename); 
     s = sr.ReadLine(); 
     string usernameFromText; 
     string passwordFromText; 
     while (sr.Peek() >= 0) 
     { 
      usernameFromText = (s.Split(','))[0]; 
      passwordFromText = (s.Split(','))[2]; 
      if (username == usernameFromText && password == passwordFromText) 
      { 
       result = "Successfully Logged in!"; 
      } 
      else if (username != usernameFromText || password != passwordFromText) 
      { 
       result = "Your Username/Password is Invalid!"; 
      } 
     } 
     sr.Close(); 

     return result; 
    } 

我的代码不读取从第二行开始,它只是挂起。

回答

4

目前尚不清楚为什么您使用sr.Peek ......并且您从未阅读过文件中的第二行。在第一个ReadLine之后,你永远不会移动文件的“光标” - 你只是反复地偷看相同的角色。如果您使用.NET 4,最简单的方法是使用File.ReadLines

foreach (string line in File.ReadLines(filename)) 
{ 
    string usernameFromText = (line.Split(','))[0]; 
    string passwordFromText = (line.Split(','))[2]; 
    if (username == usernameFromText && password == passwordFromText) 
    { 
     return "Successfully Logged in!"; 
    } 
} 
return "Your Username/Password is Invalid!"; 

如果你使用.NET 3.5,文件是不是太大了,你可以用File.ReadAllLines而不是读取整个文件......或者还有其他的选择可以一次阅读一行。

请注意,我已将逻辑更改为我所怀疑的更接近于您真正想要的内容 - 即如果的任何行匹配,则结果为成功,否则将失败。

另请注意,在原始代码中,如果在循环中引发异常,您将不会关闭阅读器 - 您应该使用using语句来避免这种情况。

另一种选择是使用LINQ:

var query = from line in File.ReadLines() 
      let split = line.Split(',') 
      select new { user = split[0], password = split[2] }; 

return query.Any(x => x.user == username && x.password == password) ? 
      "Successfully Logged in!" : "Your Username/Password is Invalid!"; 
6

在您的循环中,您保留Peek而不是调用ReadLine

2

它更易于使用File.ReadLines和读取所有线路从文件到一个字符串数组,像这样:

string[] lines = File.ReadLines("H:\\AccountInfo.txt"); 
    foreach(string oneLine in lines) 
    { 
    /// do something with line 
    } 
+2

如果您使用的是.NET 4,则使用File.ReadLines会更好......无需加载整个文件即可开始使用。 –

1
 string result; 
     StreamReader SR; 
     string S; 
     SR=File.OpenText("H:\\Account.txt"); 
     S=SR.ReadToEnd(); 
     SR.Close(); 

     string words = S; 
     words = words.Replace("\r", string.Empty); 
     List<string> splitNewLine = words.Split('\n').ToList(); 

     for (int i = 0; i <= splitNewLine.Count() - 1; i++) 
     { 
      string checkUsername = (splitNewLine[i].Split(','))[0]; 
      string checkPassword = (splitNewLine[i].Split(','))[2]; 

      if (Username == checkUsername && Password == checkPassword) 
      { 
       result = "Successfully logged in"; 
       return result; 
       break; 

      } 

     } 

     result = "Wrong Login Combination"; 
     return result; 
+0

这应该与您的上述代码密切相关。 :) – AugustusWee