Tuesday, January 22, 2013

Upload file to document library using SharePoint 2010 obect model

In this article we will discuss about how to upload a file to a document library programmatically using SharePoint 2010 object model.

Here we will upload a document to the Shared Documents document library.

You can also check out my previous posts on: RunWithElevatedPrivileges in SharePoint 2010, Redirect User to Success or Error page in SharePoint and New Features of SharePoint 2013.

using (SPSite site = new SPSite("http://SiteURL"))
using (SPWeb web = site.OpenWeb())
web.AllowUnsafeUpdates = true;

SPFolder folder = web.Folders[site.URL + "/Shared Documents/"];

byte[] content = null;

using (FileStream filestream = new FileStream(@"C:\MyDocument.docx",System.IO.FileMode.Open))
content = new byte[(int) filestream.Length];

filestream.Read(content, 0, (int) filestream.Length);


SPFile file = folder.Files.Add("MyDocument.docx", content, true);


No comments:

Post a Comment