我使用 StreamReader 的 Peek() 方法来检查是否有更多的行需要处理。我的文件中有 1000 多行,但 Peek() 在到达第 750 行时突然返回 -1。我检查过,但线#750 和#751 之间似乎没有区别。即使我删除了第 750 行和第 751 行,它仍然会在其他行中断。
以下是我的代码供您参考:
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() > -1)
{
string x = reader.ReadLine();
if (x != null)
{
//.......
}
}
}
catch (Exception ex)
{
}
finally
{
if (reader != null)
reader.Close();
if (response != null)
response.Close();
}
我试过while ((x = reader.ReadLine()) != null)
了,但是抛出了“无法访问已处置的对象”的异常。
最后我通过使用:
while (stream.CanRead && (x = reader.ReadLine()) != null)