<?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>Martijn's C# Programming Blog &#187; networking</title>
	<atom:link href="http://www.dijksterhuis.org/tag/networking/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Simple class to submit (POST) a Web form from C#</title>
		<link>http://www.dijksterhuis.org/simple-class-to-submit-post-a-web-form-from-csharp/</link>
		<comments>http://www.dijksterhuis.org/simple-class-to-submit-post-a-web-form-from-csharp/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 16:00:01 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[networking]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=697</guid>
		<description><![CDATA[Today I needed to automate posting some data to a web form from a C# program, and sure enough this is not at all that difficult. But surprisingly you need to call quite a large number of methods to get your data ready to ship. A working code example only took a few minutes to [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>Today I needed to automate posting some data to a web form from a C# program, and sure enough this is not at all that difficult. But surprisingly you need to call quite a large number of methods to get your data ready to ship. A working code example only took a few minutes to write but it took quite a bit more time to clean things up. You can find the full implementation at the end of this post.</em></p>
<p><span id="more-697"></span></p>
<p>If you like to submit a POST form to your server the following will explain how to do create the program. </p>
<p>To help with debugging I created a tiny test script on my server to see if my code was working as advertised: <em>http://www.dijksterhuis.org/test/post.php</em> Please feel free to use this script to see if your program is working correctly.</p>
<p>My wrapper code is easy to use and allows for you to add any number of parameters to the POST request:</p>
<pre class="brush: c#">
			WebPostRequest myPost = new WebPostRequest(&quot;http://www.dijksterhuis.org/test/post.php&quot;);
			myPost.Add(&quot;keyword&quot;,&quot;void&quot;);
			myPost.Add(&quot;data&quot;,&quot;hello&amp;+-[]&quot;);
</pre>
<p>I use the <em>HttpUtility.UrlEncode</em> method to ensure that all parameters containing weird symbols survive their trip over the Internet intact.</p>
<blockquote><p>string Response = myPost.GetResponse();</p></blockquote>
<p>The above function call executes the query and returns any response from the server. The test script simply echoes the parameters and their values. </p>
<pre class="brush: c#">
using System;
using System.Net;
using System.Web;
using System.Collections;
using System.IO;

namespace WebRequestExample
{

	class WebPostRequest
	{
		WebRequest theRequest;
		HttpWebResponse theResponse;
		ArrayList  theQueryData;

		public WebPostRequest(string url)
		{
			theRequest = WebRequest.Create(url);
			theRequest.Method = &quot;POST&quot;;
			theQueryData = new ArrayList();
		}

		public void Add(string key, string value)
		{
			theQueryData.Add(String.Format(&quot;{0}={1}&quot;,key,HttpUtility.UrlEncode(value)));
		}

		public string GetResponse()
		{
			// Set the encoding type
			theRequest.ContentType=&quot;application/x-www-form-urlencoded&quot;;

			// Build a string containing all the parameters
			string Parameters = String.Join(&quot;&amp;&quot;,(String[]) theQueryData.ToArray(typeof(string)));
			theRequest.ContentLength = Parameters.Length;

			// We write the parameters into the request
			StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
  			sw.Write(Parameters);
  			sw.Close();

			// Execute the query
			theResponse =  (HttpWebResponse)theRequest.GetResponse();
  			StreamReader sr = new StreamReader(theResponse.GetResponseStream());
   			return sr.ReadToEnd();
		}

	}

	class MainClass
	{
		public static void Main(string[] args)
		{
			WebPostRequest myPost = new WebPostRequest(&quot;http://www.dijksterhuis.org/test/post.php&quot;);
			myPost.Add(&quot;keyword&quot;,&quot;void&quot;);
			myPost.Add(&quot;data&quot;,&quot;hello&amp;+-[]&quot;);
			Console.WriteLine(myPost.GetResponse());
		}
	}
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/simple-class-to-submit-post-a-web-form-from-csharp/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Using the C# WebClient class to upload and download FTP files</title>
		<link>http://www.dijksterhuis.org/webclient-class-upload-download-ftp-files/</link>
		<comments>http://www.dijksterhuis.org/webclient-class-upload-download-ftp-files/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 02:18:16 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[networking]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=693</guid>
		<description><![CDATA[Your C# program has just calculated the weekly sales report and you need to upload it to the company file server. The C# System.Net.Webclient class makes this quite trivial. The same for downloading a file from the server and then parsing it for content. This post shows how you can use basic FTP actions to [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>Your C# program has just calculated the weekly sales report and you need to upload it to the company file server. The C# System.Net.Webclient class makes this quite trivial. The same for downloading a file from the server and then parsing it for content. This post shows how you can use basic FTP actions to upload, download files and either store them in memory or write them to disk.<br />
</em></p>
<p>At the end of this post you will find my <em>BasicFTPClient</em> class that implements the uploading and downloading code.</p>
<p><span id="more-693"></span></p>
<p><strong>1. Download an FTP file to disk</strong></p>
<p>If you have a file called &#8220;fileonftpserver.txt&#8221; and would like to download it to &#8220;/tmp/mydownload.txt&#8221; use the &#8220;DownloadFile&#8221; method:</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
     MyClient.DownloadFile(&quot;fileonftpserver.txt&quot;,&quot;/tmp/mydownload.txt&quot;); // c:\temp\mydownload.txt for Windows
}
catch (WebException e)
{
     Console.WriteLine(e.ToString());
}
</pre>
<p><strong>2. Download an FTP file to memory</strong></p>
<p>If you would like to directly process the file you have downloaded (and don&#8217;t need to save it to disk first) the &#8220;DownloadData&#8221; method is your friend. If you would like to print the contents of the file to the console you could try this:</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
    byte[] Data = MyClient.DownloadData(&quot;download.test&quot;);

    // Convert the data to a string
    String s = System.Text.Encoding.UTF8.GetString(Data);
    Console.WriteLine(s);
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}
</pre>
<p><strong>3. Upload a file to the FTP server</strong></p>
<p>If you have a file on disk and would like to upload it to an FTP server then use the  &#8220;UploadFile&#8221; method.</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
    MyClient.UploadFile(&quot;upload.test&quot;,&quot;/tmp/output.txt&quot;);
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}
</pre>
<p><strong>4. Upload a byte[] to the FTP server</strong></p>
<p>The &#8220;UploadData&#8221; method takes a byte array as the source of its data, allowing you to create something in memory and then save it to an FTP server. Usefull for those reports you have just generated.</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
    string MyReport = &quot;Sales figures for October 2010&quot;;
    byte[] Data = System.Text.Encoding.UTF8.GetBytes(MyReport);
    MyClient.UploadData(&quot;upload.test&quot;,Data);
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}
</pre>
<p><strong>The Mono angle</strong></p>
<p>All of the above examples work on Mono just as well as on Microsoft&#8217;s .NET. With a catch: I found two bugs in the Mono class libraries that made things quite impossible. Both were fixed by the mono team within hours of reporting them (thanks!). So if you are using the Mono CVS code for Mono 2.4 you are in luck, otherwise the following code is not going to work until the next Mono release.</p>
<p>If you come across a problem with Mono reporting a bug is trivial, you can report them at bugzilla.novell.com</p>
<p><strong>The BasicFTPClient class</strong></p>
<pre class="brush: c#">
using System;
using System.Net;
using System.IO;

namespace BasicFTPClientNamespace
{
    class BasicFTPClient
    {
        public string Username;
        public string Password;
        public string Host;
        public int Port;

        public BasicFTPClient()
        {
            Username = &quot;anonymous&quot;;
            Password = &quot;anonymous@internet.com&quot;;
            Port = 21;
            Host = &quot;&quot;;
        }

        public BasicFTPClient(string theUser, string thePassword, string theHost)
        {
            Username = theUser;
            Password = thePassword;
            Host = theHost;
            Port = 21;
        }

        private Uri BuildServerUri(string Path)
        {
            return new Uri(String.Format(&quot;ftp://{0}:{1}/{2}&quot;, Host, Port, Path));
        }

        /// &lt;summary&gt;
        /// This method downloads the given file name from the FTP server
        /// and returns a byte array containing its contents.
        /// Throws a WebException on encountering a network error.
        /// &lt;/summary&gt;

        public byte[] DownloadData(string path)
        {
            // Get the object used to communicate with the server.
            WebClient request = new WebClient();

            // Logon to the server using username + password
            request.Credentials = new NetworkCredential(Username, Password);
            return request.DownloadData(BuildServerUri(path));
        }

        /// &lt;summary&gt;
        /// This method downloads the FTP file specified by &quot;ftppath&quot; and saves
        /// it to &quot;destfile&quot;.
        /// Throws a WebException on encountering a network error.
        /// &lt;/summary&gt;
        public void DownloadFile(string ftppath, string destfile)
        {
            // Download the data
            byte[] Data = DownloadData(ftppath);

            // Save the data to disk
            FileStream fs = new FileStream(destfile, FileMode.Create);
            fs.Write(Data, 0, Data.Length);
            fs.Close();
        }

        /// &lt;summary&gt;
        /// Upload a byte[] to the FTP server
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;path&quot;&gt;Path on the FTP server (upload/myfile.txt)&lt;/param&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A byte[] containing the data to upload&lt;/param&gt;
        /// &lt;returns&gt;The server response in a byte[]&lt;/returns&gt;

        public byte[] UploadData(string path, byte[] Data)
        {
            // Get the object used to communicate with the server.
            WebClient request = new WebClient();

            // Logon to the server using username + password
            request.Credentials = new NetworkCredential(Username, Password);
            return request.UploadData(BuildServerUri(path), Data);
        }

        /// &lt;summary&gt;
        /// Load a file from disk and upload it to the FTP server
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ftppath&quot;&gt;Path on the FTP server (/upload/myfile.txt)&lt;/param&gt;
        /// &lt;param name=&quot;srcfile&quot;&gt;File on the local harddisk to upload&lt;/param&gt;
        /// &lt;returns&gt;The server response in a byte[]&lt;/returns&gt;

        public byte[] UploadFile(string ftppath, string srcfile)
        {
            // Read the data from disk
            FileStream fs = new FileStream(srcfile, FileMode.Open);
            byte[] FileData = new byte[fs.Length];

            int numBytesToRead = (int)fs.Length;
            int numBytesRead = 0;
            while (numBytesToRead &gt; 0)
            {
                // Read may return anything from 0 to numBytesToRead.
                int n = fs.Read(FileData, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached.
                if (n == 0) break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
            numBytesToRead = FileData.Length;
            fs.Close();

            // Upload the data from the buffer
            return UploadData(ftppath, FileData);
        }

    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/webclient-class-upload-download-ftp-files/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

