Drazen Bjelovuk
Drazen Bjelovuk

Reputation: 5472

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

Upvotes: 5

Views: 4042

Answers (2)

developer
developer

Reputation: 113

I'm a little late to the party but this question is still relevant. I'd like to add: MSDN Examples also demonstrate/suggest closing the stream when writing is complete.

Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);
Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}", myHttpWebRequest.ContentLength);
// Close the Stream object.
newStream.Close ();

I like @Jon's example and follow a similar pattern.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500913

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

Upvotes: 13

Related Questions