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

before

Solution

  1. static void Main(string[] args)
  2. {
  3. try
  4. {
  5. // Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
  6. using(ClientContext client = newClientContext("http://servername146/sites/test/"))
  7. {
  8. //client.Credentials = System.Net.CredentialCache.DefaultCredentials;
  9. // Assume that the web site has a library named "FormLibrary".
  10. var formLib = client.Web.Lists.GetByTitle("Documents");
  11. client.Load(formLib.RootFolder);
  12. client.ExecuteQuery();
  13. // FormTemplate path, The path should be on the local machine/server !
  14. string fileName = @ "C:\File.txt";
  15. var fileUrl = "";
  16. //Craete FormTemplate and save in the library.
  17. using(var fs = newFileStream(fileName, FileMode.Open))
  18. {
  19. var fi = newFileInfo("test.txt"); //file Title
  20. fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
  21. Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
  22. client.ExecuteQuery();
  23. }
  24. // Get library columns collection.
  25. var libFields = formLib.Fields;
  26. client.Load(libFields);
  27. client.ExecuteQuery();
  28. Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);
  29. ListItem item = newFile.ListItemAllFields;
  30. item["Title"] = "test";
  31. item.Update();
  32. client.ExecuteQuery();
  33. }
  34. } catch (Exception ex)
  35. {
  36. }
  37. }
Final Output

output

Summary: The physical document is uploaded to the SharePoint document library.