Introduction
In this article, we explored how to upload a document from a physical location to the SharePoint Document library using the 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 the document library. We will explore it using the Client Side Object model.
Before
Solution
- static void Main(string[] args)
- {
- try
- {
- // Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
- using(ClientContext client = newClientContext("http://servername146/sites/test/"))
- {
- //client.Credentials = System.Net.CredentialCache.DefaultCredentials;
- // Assume that the web site has a library named "FormLibrary".
- var formLib = client.Web.Lists.GetByTitle("Documents");
- client.Load(formLib.RootFolder);
- client.ExecuteQuery();
- // FormTemplate path, The path should be on the local machine/server !
- string fileName = @ "C:\File.txt";
- var fileUrl = "";
- //Craete FormTemplate and save in the library.
- using(var fs = newFileStream(fileName, FileMode.Open))
- {
- var fi = newFileInfo("test.txt"); //file Title
- fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
- Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
- client.ExecuteQuery();
- }
- // Get library columns collection.
- 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.
No comments:
Post a Comment