Thursday, September 11, 2014

SharePoint Client object model to upload files into the Document library

Below code uses the managed client object model to upload files to SharePoint library from the client system.
I uploaded the files to SharePoint and my requirement was to upload  into particular folder of the document library through a console application. DDL used are Microsoft.Sharepoint.client and Microsoft.Sharepoint.Client.runtime.
Below method uploads the files like PDF or Excel or word document into particular folder of the SharePoint library

public void UploadDocument(string fileName, string filePath)
        {

            ClientContext ctx = new ClientContext("http://WebApplication:777/");

            Web currentWeb = ctx.Web;
            ctx.Load(currentWeb);
            ctx.ExecuteQuery();

            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {

Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Shared Documents/" + fileName, fs, true);

            }

Microsoft.SharePoint.Client.File getFile = currentWeb.GetFileByServerRelativeUrl("/Shared Documents/" + fileName);
            ctx.Load(getFile);
            ctx.ExecuteQuery();

            //check out to make sure not to create multiple versions
            getFile.CheckOut();

            ListItem item = getFile.ListItemAllFields;
            item["testcol1"] = "T1";
            item["testDateCol2"] = DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ");
            //item["ContentTypeId"] = "0x0101";
            item.Update();
           
            // use OverwriteCheckIn type to make sure not to create multiple versions
            getFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
            ctx.ExecuteQuery();

        }

You can upload into folder by changing the code as below
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Shared Documents/Folder1" + fileName, fs, true);


You can then call the method in your application as below

UploadDocument("TestDocument.docx", @"E:\Path1\TestDocument.docx");

No comments:

Post a Comment