我正在使用以下代码来读取响应:

using (Stream MyResponseStream = hwresponse.GetResponseStream())
{
        byte[] MyBuffer = new byte[4096];
        int BytesRead;

        while (0 < (BytesRead = MyResponseStream.Read(MyBuffer, 0, MyBuffer.Length)))
        {
            ByteArrayToFile("request.txt", MyBuffer, BytesRead);
        }
}


这是写入文件的功能:

public void ByteArrayToFile(string _FileName, byte[] _ByteArray, int BytesRead)
{
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Append, System.IO.FileAccess.Write);
        _FileStream.Write(_ByteArray, 0, BytesRead);
        _FileStream.Close();
}


如果使用webclient,则会得到换行符,所有内容均已正确解析。当我使用HttpWebResponse时,换行符被剥离(不是全部,而是80%)。有什么提示为什么会这样吗?谢谢!

最佳答案

您可以使用以下代码将整个响应写入文件:

using (StreamReader MyResponseStream = new StreamReader(hwresponse.GetResponseStream()))
{
    using (StreamWriter _FileStream = new StreamWriter("request.txt", true))
    {
        _FileStream.Write(MyResponseStream.ReadToEnd());
    }
}

10-04 14:20