I am trying to use RestSharp to upload a csv to a web service but I am
running into an error. I have tried googiling the issue but all I
found was an old post that seems unrelated. If anyone has insight into
what I am doing wrong I would greatly appreciate it. I see the
following error:
This property cannot be set after writing has started.
at System.Net.HttpWebRequest.set_ContentLength(Int64 value)
at RestSharp.Http.WriteRequestBody(HttpWebRequest webRequest) in C:
\restsharp-RestSharp-109cf8e\restsharp-RestSharp-109cf8e\RestSharp
\Http.Sync.cs:line 175
at RestSharp.Http.PostPutInternal(String method) in C:\restsharp-
RestSharp-109cf8e\restsharp-RestSharp-109cf8e\RestSharp
\Http.Sync.cs:line 103
at
RestSharp.Http.Post() in C:\restsharp-RestSharp-109cf8e
\restsharp-RestSharp-109cf8e\RestSharp\Http.Sync.cs:line 39
at RestSharp.RestClient.GetResponse(IRestRequest request) in C:
\restsharp-RestSharp-109cf8e\restsharp-RestSharp-109cf8e\RestSharp
\RestClient.Sync.cs:line 88
at RestSharp.RestClient.Execute(IRestRequest request) in C:
\restsharp-RestSharp-109cf8e\restsharp-RestSharp-109cf8e\RestSharp
\RestClient.Sync.cs:line 47
The exception is thrown when setting webRequest.ContentLength.
private void WriteRequestBody(HttpWebRequest webRequest)
{
if (!HasBody)
return;
var bytes = _defaultEncoding.GetBytes(RequestBody);
webRequest.ContentLength = bytes.Length;
using (var requestStream = webRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
I am using the following code
static void UploadFile(string baseUrl, string sessionId, string arpt,
string objectName, string mapName, string fileName, string
fileNameAndPath)
{
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest("bulk/ObjectName",
Method.POST);
client.UserAgent = _userAgent;
request.AddCookie("JSESSIONID", sessionId);
request.AddCookie("ARPT", arpt);
String importXml =
"<platform>" +
"<bulk>" +
"<mapping>" + mapName + "</mapping>"
+
"</bulk>" +
"</platform>";
request.AddParameter("application/xml", importXml,
ParameterType.RequestBody);
request.AddFile(fileName, fileNameAndPath);
RestResponse response = client.Execute(request);
string content = response.Content;
}
Thank you,
-Phil