Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Necessary to close web request stream?

Which way is preferrable?

A:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();

B:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.GetRequestStream().Write(data, 0, data.Length);
like image 504
Drazen Bjelovuk Avatar asked Aug 19 '12 08:08

Drazen Bjelovuk


1 Answers

Option C instead:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (Stream reqStream = req.GetRequestStream())
{
    reqStream.Write(data, 0, data.Length);
}

But yes, I would close the request stream. It's possible that it's not absolutely required, but I wouldn't like to assume that - and in particular, unless you have good reason to believe it's not required (such as documentation), the implementation could change over time and break "lazy" code later.

If you find yourself doing this often, you could always write a utility method (possibly even as an extension method):

public static void WriteRequestData(this WebRequest request, byte[] data)
{
    using (Stream reqStream = request.GetRequestStream())
    {
        reqStream.Write(data, 0, data.Length);
    }
}

Then just call it as:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.WriteRequestData(data);
like image 90
Jon Skeet Avatar answered Oct 16 '22 15:10

Jon Skeet