This property cannot be set after writing has started! on a C# WebRequest Object
- by EBAGHAKI
I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function twice on the second time at
request.ContentLength = byteArray.Length;
it will throw an exception
This property cannot be set after writing has started!
But as you can see
dataStream.Close();
Should close the writing process! Anybody knows what's going on?
static WebRequest request;
public MainForm()
{
request = WebRequest.Create("http://localhost/admin/admin.php");
}
static string Post(string url, string data)
{
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
request.Abort();
return responseFromServer;
}