Ruchit Rami
Ruchit Rami

Reputation: 2282

Error while closing streamwriter with json content type

I am having error closing streamwriter after writing json content to the stream writer. Following is the code i am using. Can not find what is wrong. it is writing to REST service.

WebRequest request = WebRequest.Create(String.Format("{0}/EventLog", restPath));
            request.ContentType = "application/json";
            request.Method = "POST";
            request.ContentLength = jsonstring.Length;                
            System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
            sw.Write(jsonstring);                
            sw.Close();
            sw.Dispose();
            HttpWebResponse res = (HttpWebResponse)request.GetResponse();

Exception:"Cannot close stream until all bytes are written."

Upvotes: 0

Views: 863

Answers (1)

GameScripting
GameScripting

Reputation: 16992

Make sure request.ContentLength is really equal to the Content lenght (in bytes).

This throws the same error:

string data = "mydata";

WebRequest request = WebRequest.Create("http://google.de/");
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = data.Length + 1;
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
sw.Dispose();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();

Upvotes: 1

Related Questions