5

I need to upload a document to a SharePoint list or folder using the Client Side Object Model from .NET (C#). What is the best way to do this? The requirements are as follows:

  • Set metadata values
  • No limitation on file size
  • Must work with libraries that exceed the List View Threshold
2
           SPFile file = oListItem.File;

           StreamReader fsReader = new StreamReader(file.OpenBinaryStream());
           byte[] contents = null;
           using (Stream fStream = fsReader.BaseStream)
           {
               contents = new byte[fStream.Length];
               fStream.Read(contents, 0, (int)fStream.Length);
               fStream.Close();
           }


           ClientContext clientContext = new ClientContext("SITE URL");
           Web _Site = clientContext.Web;
           List _List = _Site.Lists.GetByTitle("Shared Documents");

           FileCreationInformation newFile = new FileCreationInformation();
           newFile.Content = contents;  //bytes here
           newFile.Url = _FileName;
           newFile.Overwrite = true;

           Microsoft.SharePoint.Client.File _UploadingFile =                
           _List.RootFolder.Files.Add(newFile);

           clientContext.Load(_UploadingFile);
           clientContext.ExecuteQuery();

           CamlQuery _CamlQuery = new CamlQuery();
           _CamlQuery.ViewXml = "<View><Query><Where><Contains><FieldRef Name='FileLeafRef'/><Value Type='Text'>" + _Name + "</Value>" +
                                "</Contains></Where></Query><RowLimit>100</RowLimit></View>";
           ListItemCollection _ListItemCollection = _List.GetItems(_CamlQuery);
           clientContext.Load(_ListItemCollection);
           clientContext.ExecuteQuery();

           int _count = _ListItemCollection.Count;

           ListItem _ListItem = _ListItemCollection[0];
           _ListItem["ColName1"] = ColValue1;
           _ListItem["ColName2"] = ColValue2;

           _ListItem.Update();

           clientContext.Load(_ListItem);
           clientContext.ExecuteQuery();
-1
ClientContext ctx = new ClientContext("share point url");//httP://xyz.com/yoursharepoint library
FileCreationInformation fci = new FileCreationInformation();
                    fci.Content = System.IO.File.ReadAllBytes("Your File Physical path");//D:\ filename
                    fci.Url = "SP-UploadTest";
                    fci.Overwrite = true;
                    Microsoft.SharePoint.Client.File fileToUpload = folder.Files.Add(fci);
                    ctx.Load(fileToUpload);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.