Need to close the web request stream?

Which method is preferable?

AND:

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

AT:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.GetRequestStream().Write(data, 0, data.Length);
+5
source share
2 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. Perhaps this is not entirely necessary, but I would not want to assume that - and in particular, if you have no reason to believe that this is not required (for example, documentation), the implementation may change over time and break the "lazy" code later.

If you do this often, you can always write a useful method (perhaps 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 name it like:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.WriteRequestData(data);
+13
source

, - . : MSDN / .

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

@Jon .

+1

All Articles