虽然StreamReader的循环不起作用

时间:2014-04-22 12:52:05

标签: c# while-loop streamreader

表格停止在里面工作。在cursor to c=s.Substring...

中返回while
StreamReader sr= new StreamReader("Unos.txt");
s = sr.ReadLine();
            c = s.Substring(s.IndexOf(',') + 2, (s.Length - s.IndexOf(',') + 2) - (s.Length - s.IndexOf('-') + 2));
            if ((String.Equals(cbRazred.SelectedItem.ToString(), c.Substring(0, (c.IndexOf('-')))) &&
                String.Equals(cbOdeljenje.SelectedItem.ToString(), odeljenje.ToString()))) lbSpisak.Items.Add(s.Substring(0, s.IndexOf(',')));
            while (s != null)
            {
                s = sr.ReadLine();
                c = s.Substring(s.IndexOf(',') + 2, (s.Length - s.IndexOf(',') + 2) - (s.Length - s.IndexOf('-') + 2));
                if ((String.Equals(cbRazred.SelectedItem.ToString(), c.Substring(0, (c.IndexOf('-')))) &&
                    String.Equals(cbOdeljenje.SelectedItem.ToString(), odeljenje.ToString()))) lbSpisak.Items.Add(s.Substring(0, s.IndexOf(',')));
            }
            sr.Close();

1 个答案:

答案 0 :(得分:2)

更好地使用:

while (!sr.EndOfStream)

检查你的while循环:

StreamReader sr= new StreamReader("Unos.txt");
using (sr)
{
while (!sr.EndOfStream)
{
s = sr.ReadLine();
  ///make new checks on s beacuse you getting substrings and indexes that may not exist///
  //e.g
  if (s.Length>=1)...
  //do you logic
}
}