Mostly a question on which approach would be better and when utilizing the using
keyword, would it still be neccesary to close streams programatically. If an object implements IDisposable
should using
always be used?
Link to my full answer using this sample: Stackoverflow Answer
Option 1:
WebClient webClient;
webClient = new WebClient();
string json = webClient.DownloadString(@"urlToTheJsonResponse");
MemoryStream stream = new MemoryStream((Encoding.UTF8.GetBytes(json)));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
stream.Position = 0;
GISData data = (GISData)ser.ReadObject(stream);
stream.Close();
Option 2:
WebClient webClient;
MemoryStream stream;
string json;
GISData data;
using (webClient = new WebClient())
{
json = webClient.DownloadString(@"urlToTheJsonResponse");
}
using (stream = new MemoryStream((Encoding.UTF8.GetBytes(json))))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
data = (GISData)ser.ReadObject(stream);
stream.Close();
}
using (webClient = new WebClient())
{
webClient.DownloadFile(data.href, "C:/" + data.href.Substring(data.href.LastIndexOf("/") + 1));
}