<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>BeaverBlog &#187; formfields</title>
	<atom:link href="http://blog.crazybeavers.se/index.php/archive/tag/formfields/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.crazybeavers.se</link>
	<description>A beaver bloging about webdevelopment, XML and .Net</description>
	<lastBuildDate>Tue, 26 Jul 2011 10:59:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.1</generator>
		<item>
		<title>Uploading multiple files and form fields in .Net</title>
		<link>http://blog.crazybeavers.se/index.php/archive/uploading-multiple-files-and-form-fields-in-net/</link>
		<comments>http://blog.crazybeavers.se/index.php/archive/uploading-multiple-files-and-form-fields-in-net/#comments</comments>
		<pubDate>Wed, 23 Jan 2008 15:37:27 +0000</pubDate>
		<dc:creator>Karl</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Code samples]]></category>
		<category><![CDATA[fileupload]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[formfields]]></category>
		<category><![CDATA[httpupload]]></category>
		<category><![CDATA[mimetype]]></category>
		<category><![CDATA[upload]]></category>
		<category><![CDATA[webclient]]></category>

		<guid isPermaLink="false">http://www.beaverblogg.com/index.php/archive/uploading-multiple-files-and-form-fields-in-net/</guid>
		<description><![CDATA[Recently while building a small application for a friend of mine I came across a part where I needed something that I just couldn&#8217;t find in the .Net framework. I needed to upload two files (and specify their fieldnames) and a few form fields to a webpage. I thought this would be easy just using [...]]]></description>
			<content:encoded><![CDATA[<p>
  Recently while building a small application for a friend of mine I came across a part where I needed something that I just couldn&#8217;t find in the .Net framework. I needed to upload two files (and specify their fieldnames) and a few form fields to a webpage. I thought this would be easy just using the provided WebClient class but after looking closer at it I found that it didn&#8217;t really offer anything of what I needed. Trying not to feel let down by this I started to write my own extended version of WebClient with a few new tricks that the old one couldn&#8217;t do.
</p>
<p>
  I tried to keep it as simple as possible so instead of writing new classes to hold form and file data I used two Dictionary&lt;string, string&gt; to pass the values. The Key is the fieldname and the Value the value or the path to the file. An example of uploading a few files and adding a few fields to that could look like this:</p>
<pre class="brush: csharp; title: ;">Dictionary&lt;string, string&gt; FormFiles = new Dictionary&lt;string, string&gt;();

FormFiles.Add(&quot;mypet&quot;, &quot;C:\\cat.jpg&quot;);
FormFiles.Add(&quot;me&quot;, &quot;C:\\myself.jpg&quot;);

Dictionary&lt;string, string&gt; FormFields = new Dictionary&lt;string, string&gt;();

FormFields.Add(&quot;age&quot;, &quot;22&quot;);
FormFields.Add(&quot;location&quot;, &quot;Sweden&quot;);

WebClientEx WC = new WebClientEx();

try
{
    WC.UploadData(&quot;http://www.myserver.com/upload.aspx&quot;, FormFiles, FormFields);
}
catch(WebException E)
{
    System.Console.WriteLine(&quot;Upload failed with HTTP-Code&quot; + ((HttpWebResponse)E.Response).StatusCode.ToString());
    System.Console.ReadKey();
    return;
}</pre>
<p>
  It doesn&#8217;t look that hard does it? It&#8217;s perfect to use if you need to &#8220;submit&#8221; a form on a webpage from your c# application or just need to send several files to a webserver in the same request. Below is the complete code for WebClientEx displayed. You may use it for anything you want as long as you don&#8217;t claim it as your own. If you use it in a project of yours then please write a comment or send me an email about it!
</p>
<pre class="brush: csharp; title: ;">using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using CrazyBeavers.Utils;

namespace CrazyBeavers.Net
{
    /// &lt;summary&gt;
    /// Provides common methods for sending data to and receiving data from a resource identified by a URI. This version comes with extended support for uploading files and formfields.
    /// &lt;/summary&gt;
    public class WebClientEx : WebClient
    {
        public byte[] UploadData(string Address, Dictionary&lt;string, string&gt; Files, Dictionary&lt;string, string&gt; Fields)
        {
            string Boundary = &quot;----------&quot; + DateTime.Now.Ticks.ToString(&quot;x&quot;);
            byte[] BoundaryEnd = Encoding.ASCII.GetBytes(&quot;\r\n--&quot; + Boundary + &quot;--&quot;);

            MemoryStream MS = new MemoryStream();
            byte[] Buffer;

            foreach (KeyValuePair&lt;string, string&gt; Field in Fields)
            {
                StringBuilder Header = new StringBuilder();
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;--&quot;);
                Header.Append(Boundary);
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;Content-Disposition: form-data; name=\&quot;&quot;);
                Header.Append(Field.Key);
                Header.Append(&quot;\&quot;&quot;);
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;\r\n&quot;);
                Header.Append(Field.Value);

                byte[] PostHeaderBytes = Encoding.UTF8.GetBytes(Header.ToString());

                MS.Write(PostHeaderBytes, 0, PostHeaderBytes.Length);
            }

            foreach (KeyValuePair&lt;string, string&gt; File in Files)
            {
                StringBuilder Header = new StringBuilder();
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;--&quot;);
                Header.Append(Boundary);
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;Content-Disposition: form-data; name=\&quot;&quot;);
                Header.Append(File.Key);
                Header.Append(&quot;\&quot;; filename=\&quot;&quot;);
                Header.Append(Path.GetFileName(File.Value));
                Header.Append(&quot;\&quot;&quot;);
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;Content-Type: &quot;);
                Header.Append(MimeHelper.GetMimeTypeForExtension(Path.GetExtension(File.Value)));
                Header.Append(&quot;\r\n&quot;);
                Header.Append(&quot;\r\n&quot;);

                byte[] PostHeaderBytes = Encoding.UTF8.GetBytes(Header.ToString());

                FileStream FS = new FileStream(File.Value, FileMode.Open, FileAccess.Read);

                MS.Write(PostHeaderBytes, 0, PostHeaderBytes.Length);

                Buffer = new Byte[checked((UInt32)Math.Min(4096, (Int32)FS.Length))];
                Int32 BytesRead = 0;
                while ((BytesRead = FS.Read(Buffer, 0, Buffer.Length)) != 0)
                    MS.Write(Buffer, 0, BytesRead);

                FS.Close();
            }

            MS.Write(BoundaryEnd, 0, BoundaryEnd.Length);
            MS.Position = 0;

            if (this.Headers[&quot;Content-Type&quot;] != null)
                this.Headers.Remove(&quot;Content-Type&quot;);

            this.Headers.Add(&quot;Content-Type&quot;, &quot;multipart/form-data; boundary=&quot; + Boundary);

            Buffer = new byte[MS.Length];
            MS.Read(Buffer, 0, (Int32)MS.Length);

            return this.UploadData(Address, &quot;POST&quot;, Buffer);
        }
    }
}</pre>
<p>
  I won&#8217;t go in explaining line of this code as I&#8217;ve done in a few other samples. The code isn&#8217;t that hard to understand if you have moved beyond the &#8220;beginner stage&#8221; of coding. The thing worth mentioning is the part with <em>MimeHelper.GetMimeTypeForExtension()</em> which is a small function I wrote which checks the registry for any available mimetype for a given extension. I&#8217;ve included that code below aswell since it&#8217;s needed for WebClientEx.
</p>
<pre class="brush: csharp; title: ;">using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace CrazyBeavers.Utils
{
    public static class MimeHelper
    {
        public static string GetMimeTypeForExtension(string FileExt)
        {
            if (!FileExt.StartsWith(&quot;.&quot;))
                FileExt = &quot;.&quot; + FileExt;

            string Mime = &quot;application/octet-stream&quot;;

            RegistryKey Classes = Registry.ClassesRoot;

            RegistryKey FileKey = Classes.OpenSubKey(FileExt);
            if (FileKey != null)
            {
                Mime = (string)FileKey.GetValue(&quot;Content Type&quot;, &quot;application/octet-stream&quot;);
                FileKey.Close();
            }
            Classes.Close();
            return Mime;
        }
    }
}</pre>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.crazybeavers.se/index.php/archive/uploading-multiple-files-and-form-fields-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

