Introduction
In this article we explored how to upload a document from physical location to SharePoint Document library using client side object model. This can be achieved using server side or SharePoint Web Services.
Scenario
Many times there is a requirement to upload a document from a physical path to document library. We will explore it using Client Side Object model.
Before
Solution
- static void Main(string[] args)
- {
-
- try
- {
-
- using(ClientContext client = newClientContext("http://servername146/sites/test/"))
- {
-
-
-
- var formLib = client.Web.Lists.GetByTitle("Documents");
- client.Load(formLib.RootFolder);
- client.ExecuteQuery();
-
-
- string fileName = @ "C:\File.txt";
-
- var fileUrl = "";
-
-
- using(var fs = newFileStream(fileName, FileMode.Open))
- {
- var fi = newFileInfo("test.txt");
- fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
- Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
- client.ExecuteQuery();
- }
-
-
- var libFields = formLib.Fields;
- client.Load(libFields);
- client.ExecuteQuery();
-
- Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);
-
- ListItem item = newFile.ListItemAllFields;
-
- item["Title"] = "test";
- item.Update();
- client.ExecuteQuery();
- }
-
- } catch (Exception ex)
- {
-
- }
-
- }
Final Output
Summary: The physical document is uploaded to the SharePoint document library.