在将json内容写入流编写器后,我在关闭streamwriter时遇到错误。 以下是我正在使用的代码。找不到有什么问题。它正在写入REST服务。
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();
异常:“在写入所有字节之前无法关闭流。”
答案 0 :(得分:1)
确保request.ContentLength
确实等于内容长度(以字节为单位)。
这会引发同样的错误:
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();