Monday, July 25, 2011

Programmatically upload documents in SharePoint 2010

Programmatically upload documents in SharePoint 2010

This article is about uploading documents to a Document library in Sharepoint 2010 using C# code.


Open Visual studio 2010, Create new Sharepoint 2010 project. Select VisualWebPart template and name it as ‘DocumentUpload

Mention the site name and select ‘Deploy as a farm solution’ option.

Rename ‘VisualWebPart1’ as ‘DocumentUploadWebPart’.

Open’ DocumentUploadWebPart’ in design mode. Insert ‘FileUpload’ and ‘Button’ controls to the webpart. Select Button and go to properties. Change ID to btnUpload and Text to Upload.

At the solution explorer add the following assemblies to the Reference.

  • · Microsoft.SharePoint.Client.Runtime.dll
  • · Microsoft.SharePoint.Client.dll

Double click on Upload button to go to code view.

Include the following reference at the top.

using SP = Microsoft.SharePoint.Client;

Insert the following code to the Upload button click event

protected void btnUpload_Click(object sender, EventArgs e)


string library = "Shared Documents";

SP.ClientContext ctx = new SP.ClientContext(@"http://sharepoint-pc:3395/sites/mcts");

var web = ctx.Web;

var fciNewFileFromComputer = new SP.FileCreationInformation();

fciNewFileFromComputer.Content = System.IO.File.ReadAllBytes(FileUpload1.PostedFile.FileName);

fciNewFileFromComputer.Url = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);

SP.List docs = web.Lists.GetByTitle(library);

SP.File uploadedFile = docs.RootFolder.Files.Add(fciNewFileFromComputer);



Build and deploy the feature. You will find this web part under Custom category when you insert webparts to the pages.

Thats it!!

No comments:

Post a Comment