Showing posts with label IIS. Show all posts
Showing posts with label IIS. Show all posts

Thursday, October 6, 2011

How to upload/download file to/from server using WebClient method…?

Today’s business applications are working on client server architecture and on timely basis files are being uploaded to server from client or vice versa.

In ASP.Net we can upload a file to server using File-Upload control. But what-if we want to upload a file automatically or programmatically to the server using Windows application, Windows Service or Web application?

The possible ways to upload a file to server are follows:
  • FTP Upload 
  • HTTP Upload
  • ...
Here I will show how to upload/download a file using HTTP method (i.e. commonly known as Web Client method).

In Web Client method we require a virtual directory to which file is to be upload under domain name (i.e. http://www.YourDomainName.com/ClientFiles/). So we are going to upload files to “ClientFiles” directory.

Note: You need to install and configure WebDAV (Web Distributed Authoring and Versioning) in IIS. Click here for an article on Installing and Configuring WebDAV on IIS 7.

Code to upload a file on Server using WebClient method:

System.Net.WebClient webClient = new System.Net.WebClient();
string sourceFilePath = @"D:\MyDocuments\DataFile.xml" ;
string webAddress = "http://www.YourDomainName.com/ClientFiles/";
string destinationFilePath= webAddress + "DataFile.xml";
webClient.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
webClient.UploadFile(destinationFilePath, "PUT", sourceFilePath);
webClient.Dispose();


Code to download a file from Server using WebClient method:

System.Net.WebClient webClient = new System.Net.WebClient();
string webAddress = "http://www.YourDomainName.com/ClientFiles/";
string sourceFilePath = webAddress + "DataFile.xml";
string destinationFilePath = @"D:\MyDocuments\DataFile.xml";
webClient.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
webClient.DownloadFile(sourceFilePath, destinationFilePath);
webClient.Dispose();




Learn by diving in Programming Ocean...
Happy Programming!!!