I am trying to hit a SOAP-based, MTOM service which accepts multipart attachment. Here is how I create the request from C#:
var request = (HttpWebRequest)WebRequest.Create("...skipping URL...");
request.ContentType = @"multipart/related;charset=""UTF-8"";type=""application/xop+xml"";start=""<http://tempuri.org/0>"";boundary=""uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1"";start-info=""application/soap+xml""";
request.Method = "POST";
request.Timeout = 30000;
request.Headers.Add("MIME-Version", "1.0");
request.Headers.Add("Accept-Encoding", "gzip, deflate");
var postData = @"--uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1
Content-ID: <http://tempuri.org/0>
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type=""text/xml""
[Skipping the SOAP envelope that goes here...]
--uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1
Content-ID: <http://tempuri.org/1/636875796573424479>
Content-Transfer-Encoding: binary
Content-Type: application/octet-stream
" + Encoding.UTF8.GetString(File.ReadAllBytes(@"C:\Users\User\Desktop\Sample.pdf")) + @"
--uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1--";
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
writer.Write(postData);
My question is this: Since I know the content type must be application/octet-stream and the transfer encoding must be binary, am I correctly reading the binary data of my PDF file for submission to this service? Is it correct to use Encoding.UTF8.GetString(File.ReadAllBytes(@"C:\Users\User\Desktop\Sample.pdf"))
here or is it incorrect? How should I create the request to send the attachment?
Edit: Would it be more correct to do something like this?
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
using (var attachment = new FileStream(@"C:\Users\User\Desktop\Sample.pdf", FileMode.Open, FileAccess.Read))
{
writer.Write(postDataPrefix); // Add everything up to the start of the attachment binary.
writer.Flush();
stream.Flush();
attachment.CopyTo(stream); // Add the actual attachment binary.
writer.Flush();
stream.Flush();
writer.Write(postDataSuffix); // Add everything after the attachment binary.
writer.Flush();
stream.Flush();
}