2

i'm working on download manager project and i'm using :

public Stream GetStream(string url)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    return response.GetResponseStream();
}

then use the returned stream as input stream and FileStream as output stream in while statement :

Stream InputStream = GetStream("http://test_url/test.zip");
Stream OutputStream = new FileStream("d:\\test.zip", FileMode.Create, FileAccess.Write));
do
{
    readSize = InputStream.Read(buffer, 0, buffSize);
    OutputStream.Write(buffer, 0, (int)readSize);
}
while (readSize > 0);

when downloading a file over 50MB using my 256kpps connection after about 20 - 30 MB, readSize become 0 without errors

my question is : is there anything wrong with Response object , is it disposed???? or what is the problem?

Thank you in advance, and i'm sorry if i can't explain better.

Omar
  • 31
  • 7
  • 1
    What do you mean by something like in your question - is that your code or is it not the code that you are running. It will be easier to help if you provide the actual code that you are working with – PyNEwbie Nov 27 '12 at 00:59
  • You will need to post actual code, the example you give doesn't make any sense. And why would you be attempting to read from the Response stream? That's meant to be writen to. – Steve Py Nov 27 '12 at 05:42
  • hi, i edited my post so i think it's clear now, for @steve-py : i think that response stream is for reading; – Omar Nov 28 '12 at 18:39
  • Does your code work with smaller files? – nick_w Nov 28 '12 at 21:58

1 Answers1

2

You aren't disposing your HttpWebRequest / HttpWebResponse objects, which could be causing a problem - there is a built-in limit to the number of concurrent connections to the same server.

You should be doing something like:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using(Stream responseStream = response.GetResponseStream())
    {
        using(Stream outputStream = new FileStream(...))
        {
            responseStream.CopyTo(outputStream);
        }
    }
}

Stream.CopyTo is new in .NET 4.0. If you're using .NET <= 3.x you'll need to write your own.

Community
  • 1
  • 1
Joe
  • 122,218
  • 32
  • 205
  • 338
  • Thank you @Joe but you are doing all job in one place, my question was about splitting request and response in another function and use the stream returned by it in a second place. regarding disposing : i actually did that , so i'm afraid that response stream was separated from its own response and because of that the stream can't read any more. – Omar Nov 28 '12 at 21:34