So I noticed im starting to re-use code over and over again and its starting to look ugly. Each button click I noticed that some of the code (For POST) is the same apart from the uri. Is there any way I could manage the below code in a better way?
private void AddTag_Click(object sender, EventArgs e)
{
string uriAddTagtoGroup = string.Format("http://localhost:8000/Service/AddTagtoGroup/{0}/{1}", textBox6.Text, textBox7.Text);
byte[] arr = Encoding.UTF8.GetBytes(uriAddTagtoGroup);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uriAddTagtoGroup);
req.Method = "POST";
req.ContentType = "application/xml";
req.ContentLength = arr.Length;
Stream reqStrm = req.GetRequestStream();
reqStrm.Write(arr, 0, arr.Length);
reqStrm.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
MessageBox.Show(resp.StatusDescription);
reqStrm.Close();
resp.Close();
}
This code can be pulled into a method with some parameters for the arguments that change:
For disposable stuff (things that implement
IDisposable), there is also theusingkeyword: