title: Trying to sending this multi-part SOAP request with an attachment to a web service
body: <p>I am trying to hit a SOAP-based, MTOM service which accepts multipart attachment. Here is how I create the request from C#:</p>
  
  <pre><code>var request = (HttpWebRequest)WebRequest.Create("...skipping URL...");
  request.ContentType = @"multipart/related;charset=""UTF-8"";type=""application/xop+xml"";start=""&lt;http://tempuri.org/0&gt;"";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: &lt;http://tempuri.org/0&gt;
  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: &lt;http://tempuri.org/1/636875796573424479&gt;
  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);
  </code></pre>
  
  <p>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 <code>Encoding.UTF8.GetString(File.ReadAllBytes(@"C:\Users\User\Desktop\Sample.pdf"))</code> here or is it incorrect? How should I create the request to send the attachment?</p>
  
  <p><strong>Edit</strong>: Would it be more correct to do something like this?</p>
  
  <pre><code>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();
  }
  </code></pre>