BeginGetResponse is the method you need. It allows you to read the response stream incrementally:
class Program
{
static void Main(string[] args)
{
WebRequest request = WebRequest.Create("http://stream.twitter.com/spritzer.json");
request.Credentials = new NetworkCredential("username", "password");
request.BeginGetResponse(ar =>
{
var req = (WebRequest)ar.AsyncState;
// TODO: Add exception handling: EndGetResponse could throw
using (var response = req.EndGetResponse(ar))
using (var reader = new StreamReader(response.GetResponseStream()))
{
// This loop goes as long as twitter is streaming
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
}
}, request);
// Press Enter to stop program
Console.ReadLine();
}
}
Or if you feel more comfortable with WebClient (I personnally prefer it over WebRequest):
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("username", "password");
client.OpenReadCompleted += (sender, e) =>
{
using (var reader = new StreamReader(e.Result))
{
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
}
};
client.OpenReadAsync(new Uri("http://stream.twitter.com/spritzer.json"));
}
Console.ReadLine();