Friday, July 9, 2010

Upload or download a file to SharePoint by using WebClient

Upload or download file in Share Point is faster by using WebClient class over Share Point web services. Here is the code snippet:

Upload a file to Share Point Site from local system:

//create a object of WebClient
WebClient client = new WebClient();

//provide the credentials to access share point site

//NetworkCredential is used to provide credentials when user is in different account or domain

client.Credentials = new NetworkCredential("username", "password", "domain");

//if user windows credentials are same as share point credentials then DefaultCredentials property of
CredentialCache can be used

client.Credentials=CredentialCache.DefaultCredentials;

//UploadFile method of WebRequest will be used to upload file from local system to share point location.

client.UploadFile(new Uri("http://mossserver/File Name"), "PUT","c:\\filename");

Note: While uploading a new file to share point file should already exist at share point site.

Download a file from Share Point Site to local system:


//create a object of WebClient
WebClient client = new WebClient();

//provide the credentials to access share point site

//NetworkCredential method is used to provide credentials when user is in
in different account or domain

client.Credentials = new NetworkCredential("username", "password", "domain");

//if user windows credentials are same as share point credentials then DefaultCredentials property of CredentialCache can be used

client.Credentials=CredentialCache.DefaultCredentials;

//Download method of WebRequest will be used to download file from share point to local system.

client.DownloadFile(new Uri(http://mossserver/File Name), "c:\\");

1 comment:

  1. What about when the SharePoint credentials are different than the Windows credentials?

    ReplyDelete