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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With