title: C#: Using StreamReader to read line from txt file, but Peek() return -1 even there are a lot of lines left
body: <p>I use Peek() method of StreamReader to check whether there are more lines need to be processed. There are more than 1000 lines in my file, but Peek() suddenly return -1 when it reachs line#750. I checked but seems no differences between line#750 and #751. Even I deleted line#750 and 751, it will still break up at other line.</p>
  
  <p>Below are my codes for your information:</p>
  
  <pre><code>try
  {
      String ftpserver = ftp + filename;
      reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
      reqFTP.UsePassive = false;
      reqFTP.UseBinary = true;
      reqFTP.Proxy = null;
      reqFTP.Credentials = new NetworkCredential(username, password);
  
      reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
      response = (FtpWebResponse)reqFTP.GetResponse();
      stream = response.GetResponseStream();
      reader = new StreamReader(stream, ConfigHelper.MyEncoding);
      while (reader.Peek() &gt; -1)
      {
          string x = reader.ReadLine();
          if (x != null)
          {
            //.......
           }
      }
  }
  catch (Exception ex)
  {
  }
  finally
  {
      if (reader != null)
          reader.Close();
      if (response != null)
          response.Close();
  }
  </code></pre>
  
  <p>I tried <code>while ((x = reader.ReadLine()) != null)</code>, but an exception of "Cannot access a disposed object" was thrown out.</p>
  
  <p>Finally I figured it out by using:
  <code>while (stream.CanRead &amp;&amp; (x = reader.ReadLine()) != null)</code></p>