title: How to save a binary file submitted through an HTML form field?
body: <p>I need to add a function to an existing CGI application that is written in C# as a Windows Console app.  I need to add the ability for a few users to be able to submit a datafile for processing.  The datafiles can be either text/csv files or various binary files (.xls, .pdf).  I have a simple test HTML form set up using an  field for selecting/submitting the file.  That all works fine.  I can save a text file on the server with no problems.  But how do I save a binary file?  I'm sure it's easy to do but I've been unable to figure it out.</p>
  
  <p>Below is some sample code that works for saving text files:</p>
  
  <pre><code>String formData = Console.In.ReadToEnd();
  string boundary = string.Empty;
  string[] cPairs = cType.Split(new string[] { "; " }, StringSplitOptions.None);
  foreach (string pair in cPairs) {
      //finds the 'boundary' text
      if (pair.Contains("boundary"))
          boundary = "--" + pair.Split('=')[1];
  }
  
  //splits on the 'boundary' to get individual form fields/sections
  string[] sections = rawParams.Split(new string[] { boundary }, StringSplitOptions.RemoveEmptyEntries);
  
  // parse each section
  foreach (string section in sections) {
      string[] parts = section.Split(new string[] { "; ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
      if (parts[1].Equals("name=\"dFile\"")) { // 'dFile' is the form field-name for the datafile
          //below lines get the filename
          Regex regx = new Regex("filename=\"(.+)\"", RegexOptions.IgnoreCase);
          Match fPath = regx.Match(parts[2]);
          FileInfo fi = new FileInfo(fPath.Groups[1].Value);
          regx = new Regex("([-A-Z0-9_ .]+)", RegexOptions.IgnoreCase);
          Match fname = regx.Match(fi.Name);
  
          //below lines save the file contents to a text file; starts at index 4 of the 'parts' array
          if (fname.Groups[1].Success) {
              TextWriter tw = new StreamWriter(fname.Groups[1].Value);
              for (int i = 4; i &lt; parts.Length; i++) {
                  tw.WriteLine(parts[i]);
              }
              tw.Close();
          }
      }
      else {
          // parse other non-file form fields
      }
  }
  </code></pre>
  
  <p>The key part is the saving to a file.  How would I do that for a binary file?
     Dave</p>