Free Information Technology Magazines and eBooks

Saturday, March 28, 2009

C#: Download File from website using Web Client Class

Starting next week we are to start the integration testing of our automated gate system project. We have two (2) different business servers that needs to communicate. These two busines systems have different platform, one is using Java+MySQL while the other one is on .NET+Legacy Database. Aside from plain messages, most of the time, B2B applications today also exchange files. Ofcourse we can do it using File Transfer Protocol (FTP) applications but since message exchanges often done through web service then we can do the same thing with file transfer. We can achieve this by using Webclient of System.Net namespace. Below is a sample code for starters.


using System;
using System.Net;
using Myapp.Properties;

namespace MyApp
{
public class Test
{
static void Main(string[] args)
{
string website ="http://www.fryan0911.com/webclientsample.zip";
string downloadfolder = Settings.Default.DownloadFolder;

try
{
WebClient wc = new WebClient();
wc.DownloadFile(website, downloadfolder);
Console.WriteLine("Web file has been downloaded to " + downloadfolder);
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}



No comments: