title: C# Upload file error - Corrupt form data: no leading boundary
body: <p>I am using this code below to authenticate and upload file to a website, but I am getting an error "Corrupt form data: no leading boundary".</p>
  
  <p>In the Fiddler I see this, ( I see the <strong>exact same</strong> thing when I upload the file using <strong>browser</strong>), not sure why I am getting an error when I am doing using <strong>C# HttpWebRequest/WebClient</strong></p>
  
  <p><strong>Fiddler Info:</strong></p>
  
  <pre><code>------WebKitFormBoundary9ewWOMyBmk0YAhTL
  Content-Disposition: form-data; name="FileSubmitted"; filename="SAMPLE_0001.xls"
  Content-Type: application/vnd.ms-excel
  
  ------WebKitFormBoundary9ewWOMyBmk0YAhTL
  Content-Disposition: form-data; name="FileSubmittedValue" 
  
  C:\path\SAMPLE_0001.xls
  ------WebKitFormBoundary9ewWOMyBmk0YAhTL--
  </code></pre>
  
  <p><strong>Assumptions:</strong> </p>
  
  <p>I <strong>hard coded</strong> the '<strong>boundary</strong>' value, because I am not sure how to get the 'boundary' value after login.</p>
  
  <p><strong>Code:</strong> <em>Copied from Stackoverflow</em></p>
  
  <pre><code>static void Main()
  {
      NameValueCollection nvCollection = new NameValueCollection();
      CookieAwareWebClient webClient = new CookieAwareWebClient();
  
      nvCollection.Clear();
      nvCollection["Name"] = "ABC";
      nvCollection["Password"] = "XYZ";
      //Login to the Site
      byte[] responseBytes = webClient.UploadValues("https://www.somesite.com/login.cfm", "POST", nvCollection);
      string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);
      //Get Cookies
      CookieCollection cookies = webClient.CookieContainer.GetCookies(new Uri("https://www.somesite.com/login.cfm"));
      //
      string URL = "https://www.somesite.com/app/request.cfm";
      string boundary = "----WebKitFormBoundary9ewWOMyBmk0YAhTL";
      string FilePath = "C:\\Users\\user.name\\Desktop\\SAMPLE_0001.xls";
      byte[] fileData = GetMultipartFormData(new Dictionary&lt;string, object&gt;() { { "FileSubmitted", FilePath } }, boundary);
      PostForm(URL, "", "", fileData, boundary, cookies);
  }
  private static byte[] GetMultipartFormData(Dictionary&lt;string, object&gt; postParameters, string boundary)
  {
      Encoding encoding = Encoding.UTF8;
      Stream formDataStream = new System.IO.MemoryStream();
      bool needsCLRF = false;
      foreach (var param in postParameters)
      {
          // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
          // Skip it on the first parameter, add it to subsequent parameters.
          if (needsCLRF)
              formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
          needsCLRF = true;
          {
              string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                  boundary,
                  param.Key,
                  param.Value,
                  "application/vnd.ms-excel");
              formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
              string postData2 = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\" \r\n\r\n{2}",
                  boundary,
                  "FileSubmittedValue",
                  "C:\\path\\SAMPLE_0001.xls");
              formDataStream.Write(encoding.GetBytes(postData2), 0, encoding.GetByteCount(postData2));
          }
      }
      // Add the end of the request.  Start with a newline
      string footer = "\r\n--" + boundary + "--\r\n";
      formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
      // Dump the Stream into a byte[]
      formDataStream.Position = 0;
      byte[] formData = new byte[formDataStream.Length];
      formDataStream.Read(formData, 0, formData.Length);
      formDataStream.Close();
      return formData;
  }   
  private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData, string boundary, CookieCollection cookies)
  {
      HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
      if (request == null)
      {
          throw new NullReferenceException("request is not a http request");
      }
      // Set up the request properties.
      request.UserAgent = userAgent;
      request.ContentLength = formData.Length;
      request.ContentType = "multipart/form-data; boundary=" + boundary;
      request.Method = "POST";
      request.KeepAlive = true;
      request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
      request.CookieContainer = new CookieContainer();
      request.CookieContainer.Add(cookies);
      request.Host = "secure.somesite.com";
      request.Referer = String.Format("https://secure.somesite.com/app/request.cfm?CFID={0}&amp;CFTOKEN={1}", cookies[0].Value, cookies[1].Value);
      request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
      // Send the form data to the request.
      using (Stream requestStream = request.GetRequestStream())
      {
          requestStream.Write(formData, 0, formData.Length);
          requestStream.Close();
      }
      try
      {
          return request.GetResponse() as HttpWebResponse;
      }
      catch (WebException wex)
      {
          var pageContent = new StreamReader(wex.Response.GetResponseStream())
                                .ReadToEnd();
          return null;
      }
      return null;       
  }
  </code></pre>
  
  <p><strong>Error:</strong>  </p>
  
  <pre><code>&lt;head&gt;&lt;title&gt;JRun Servlet Error&lt;/title&gt;&lt;/head&gt;&lt;h1&gt;500 &lt;/h1&gt;&lt;body&gt;
  &lt;pre&gt;
  Corrupt form data: no leading boundary:  != ------WebKitFormBoundary9ewWOMyBmk0YAhTL&lt;/pre&gt;&lt;br&gt;&lt;pre&gt;
  java.io.IOException: Corrupt form data: no leading boundary:  != ------WebKitFormBoundary9ewWOMyBmk0YAhTL
      at com.oreilly.servlet.multipart.MultipartParser.&amp;lt;init&amp;gt;(MultipartParser.java:176)
      at com.oreilly.servlet.multipart.MultipartParser.&amp;lt;init&amp;gt;(MultipartParser.java:95)
      at coldfusion.filter.FormScope.fillMultipart(FormScope.java:170)
      at coldfusion.filter.FusionContext.SymTab_initForRequest(FusionContext.java:435)
      at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:33)
      at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22)
      at coldfusion.filter.RequestThrottleFilter.invoke(RequestThrottleFilter.java:126)
      at coldfusion.CfmServlet.service(CfmServlet.java:175)
      at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89)
      at jrun.servlet.FilterChain.doFilter(FilterChain.java:86)
      at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42)
      at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46)
      at jrun.servlet.FilterChain.doFilter(FilterChain.java:94)
      at jrun.servlet.FilterChain.service(FilterChain.java:101)
      at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106)
      at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42)
      at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286)
      at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543)
      at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203)
      at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428)
      at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)
  &lt;/pre&gt;&lt;/body&gt;
  </code></pre>
  
  <p><strong>Don't Knows:</strong> Since I copied this source code from Stackoverflow, I don't know if the file really getting uploaded to C:\Path folder on server (look at the Fiddler data).</p>
  
  <p><strong>Update</strong>: When I try to upload file using browser I see <strong>Content-Length: 49504</strong>, but when I try using C# program <strong>Content-Length: 385</strong> (Even when I use the same file in both browser and C# program)</p>
  
  <p>Also, when I try now I am getting "<strong>No data was received in the uploaded file SAMPLE_0001.xls</strong>"</p>