Search code examples
c#httpwebresponsestrip

HttpWebResponse stripping newline characters


I'm using the following code to read the response:

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);
        }
}

This is the function to write to a file:

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();
}

If I use webclient, I get new lines everything is parsed correctly. When I use HttpWebResponse new line characters get stripped (not all, but 80%). Any hints why this is happening? Thanks!


Solution

  • You could just use the following code to write the entire response to a file:

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