make a http request with a custom body as multipart form data in csharp
main.cs
// Set the form fields and filenamestring formFieldName = "file";
string fileName = "example.txt";
string contentType = "text/plain";
// Convert the file to a byte arraybyte[] fileBytes = File.ReadAllBytes(fileName);
// Set the boundary string for the multipart form datastring boundary = "------------------------" + Guid.NewGuid().ToString("N");
// Build the multipart form bodyStringBuilder sb = new StringBuilder();
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: form-data; name=\"" + formFieldName + "\"; filename=\"" + fileName + "\"");
sb.AppendLine("Content-Type: " + contentType);
sb.AppendLine();
sb.Append(Encoding.UTF8.GetString(fileBytes));
sb.AppendLine();
sb.AppendLine("--" + boundary + "--");
// Set the request url and methodstring requestUrl = "http://example.com/upload";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
// Set the form body on the request byte[] requestBodyBytes = Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = requestBodyBytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
}
// Send the request and get the responseusing (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Handle the response}