Thursday, August 11, 2011

Add / Upload document to Document Library using SharePoint Object Model

Below is the code to upload document to SharePoint Document Library with all the metadata you wanted to update.


String fileToUpload = @"C:\FileNamePath.txt";
String sharePointSite = "http://urSharePointsite.com/sites/";
String documentLibraryName = "Shared Documents";

using
(SPSite oSite = new SPSite(sharePointSite))
{
   using
(SPWeb oWeb = oSite.OpenWeb())
   {
        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        //upload document
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, true);

        SPListItem spLibItem = spfile.Item;


        spLibItem["Title"] = "Document Title";
        spLibItem["Field2"] = "Field2 Value";
        spLibItem.Update();
     }
}




Share:

0 comments:

Post a Comment