make a http request with a custom body as multipart form data in csharp

main.cs
// Set the form fields and filename
string formFieldName = "file";
string fileName = "example.txt";
string contentType = "text/plain";

// Convert the file to a byte array
byte[] fileBytes = File.ReadAllBytes(fileName);

// Set the boundary string for the multipart form data
string boundary = "------------------------" + Guid.NewGuid().ToString("N");

// Build the multipart form body
StringBuilder 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 method
string 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 response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    // Handle the response
}
1418 chars
41 lines

gistlibby LogSnag