<p>I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse:</p>

<pre><code>// response is an HttpWebResponse
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd(); // throws exception...
</code></pre>

<p>When the <code>reader.ReadToEnd()</code> method is called I'm getting the following System.IO.IOException: <strong>Unable to read data from the transport connection: The connection was closed.</strong></p>

<p>The above code works just fine when server returns a "non-chunked" response.</p>

<p>The only way I've been able to get it to work is to use HTTP/1.0 for the initial request (instead of HTTP/1.1, the default) but this seems like a lame work-around.</p>

<p>Any ideas?</p>

<hr>

<p>@Chuck</p>

<p>Your solution works pretty good. It still throws the same IOExeception on the last Read(). But after inspecting the contents of the StringBuilder it looks like all the data has been received. So perhaps I just need to wrap the Read() in a try-catch and swallow the "error".</p>

[{'answer_id': 17236, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': '<p>Haven\'t tried it this with a "chunked" response but would something like this work? </p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nByte[] buf = new byte[8192];\nStream resStream = response.GetResponseStream();\nstring tmpString = null;\nint count = 0;\ndo\n{\n     count = resStream.Read(buf, 0, buf.Length);\n     if(count != 0)\n     {\n          tmpString = Encoding.ASCII.GetString(buf, 0, count);\n          sb.Append(tmpString);\n     }\n}while (count &gt; 0);\n</code></pre>\n'}, {'answer_id': 352440, 'author': 'Liam Corner', 'author_id': 44565, 'author_profile': 'https://Stackoverflow.com/users/44565', 'pm_score': -1, 'selected': False, 'text': "<p>I've had the same problem (which is how I ended up here :-).  Eventually tracked it down to the fact that the chunked stream wasn't valid - the final zero length chunk was missing.  I came up with the following code which handles both valid and invalid chunked streams.</p>\n\n<pre><code>using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))\n{\n    StringBuilder sb = new StringBuilder();\n\n    try\n    {\n        while (!sr.EndOfStream)\n        {\n            sb.Append((char)sr.Read());\n        }\n    }\n    catch (System.IO.IOException)\n    { }\n\n    string content = sb.ToString();\n}\n</code></pre>\n"}, {'answer_id': 15497373, 'author': 'user2186152', 'author_id': 2186152, 'author_profile': 'https://Stackoverflow.com/users/2186152', 'pm_score': 1, 'selected': False, 'text': '<p>I am working on a similar problem. The .net HttpWebRequest and HttpWebRequest handle cookies and redirects automatically but they do not handle chunked content on the response body automatically.</p>\n<p>This is perhaps because chunked content may contain more than simple data (i.e.: chunk names, trailing headers).</p>\n<p>Simply reading the stream and ignoring the EOF exception will not work as the stream contains more than the desired content. The stream will contain chunks and each chunk begins by declaring its size. If the stream is simply read from beginning to end the final data will contain the chunk meta-data (and in case where it is gziped content it will fail the CRC check when decompressing).</p>\n<p>To solve the problem it is necessary to manually parse the stream, removing the chunk size from each chunk (as well as the CR LF delimitors), detecting the final chunk and keeping only the chunk data. There likely is a library out there somewhere that does this, I have not found it yet.</p>\n<p>Usefull resources :</p>\n<p><a href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Chunked_transfer_encoding</a>\n<a href="https://www.rfc-editor.org/rfc/rfc2616#section-3.6.1" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc2616#section-3.6.1</a></p>\n'}, {'answer_id': 57149944, 'author': 'Steven Craft', 'author_id': 312000, 'author_profile': 'https://Stackoverflow.com/users/312000', 'pm_score': 0, 'selected': False, 'text': '<p>After trying a lot of snippets from StackOverflow and Google, ultimately I found this to work the best (assuming you know the data a UTF8 string, if not, you can just keep the byte array and process appropriately):</p>\n\n<pre><code>byte[] data;\nvar responseStream = response.GetResponseStream();\nvar reader = new StreamReader(responseStream, Encoding.UTF8);\ndata = Encoding.UTF8.GetBytes(reader.ReadToEnd());\nreturn Encoding.Default.GetString(data.ToArray());\n</code></pre>\n\n<p>I found other variations work most of the time, but occasionally truncate the data. I got this snippet from:</p>\n\n<p><a href="https://social.msdn.microsoft.com/Forums/en-US/4f28d99d-9794-434b-8b78-7f9245c099c4/problems-with-httpwebrequest-and-transferencoding-chunked?forum=ncl" rel="nofollow noreferrer">https://social.msdn.microsoft.com/Forums/en-US/4f28d99d-9794-434b-8b78-7f9245c099c4/problems-with-httpwebrequest-and-transferencoding-chunked?forum=ncl</a></p>\n'}, {'answer_id': 70376652, 'author': 'Vanden', 'author_id': 1360800, 'author_profile': 'https://Stackoverflow.com/users/1360800', 'pm_score': 0, 'selected': False, 'text': '<p>It is funny. During playing with the request header and removing &quot;Accept-Encoding: gzip,deflate&quot; the server in my usecase did answer in a plain ascii manner and no longer with chunked, encoded snippets. Maybe you should give it a try and keep &quot;Accept-Encoding: gzip,deflate&quot; away. The idea came while reading the upper mentioned wiki in topic about using compression.</p>\n'}]
['https://Stackoverflow.com/questions/16998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2047/']