I'm trying to programmatically add an item to a document library in the Sharepoint 2013 Preview that comes with Office 365. I've managed to add an item by using the code fragment below (from a provider-hosted app in C#).

However I can't seem to find an example for doing the same thing with a document library (neither in MSDN documentation nor with Google).

var creationInformation = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem listItem = list.AddItem(creationInformation);
listItem.FieldValues["Foo"] = "Bar";

I'd be very glad if someone could give me some hints regarding this problem. I'm not exclusively interested in a C# solution, if you know how to do it with JavaScript or via REST API then I'd be happy to hear about that as well. Thanks in advance!

1 Answer 1


With C# you can do it this way -

SPFolder doclib = web.Folders["Document Library"];
doclib.Files.Add(filename, bytestream_ofthe_file);

this is one simple snippet, not the complete solution, you can easily get the bytestream of a file with C#. It's better to mark AllowUnsafeUpdate to true just to avoid some issues, make it false later.

I am not that much sure about REST API, and with the help of javascript from client side - it's little bit tricky to get the bytestream, otherwise it can be done with calling service from js also

Edit: Here's a working snippet:

List documentLibrary = web.Lists.GetByTitle("Documents");
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = System.IO.File.ReadAllBytes(@"C:\foo.docx");
fileCreationInformation.Url = "foo.docx";
Microsoft.SharePoint.Client.File file = documentLibrary.RootFolder.Files.Add(fileCreationInformation);

Check this link for more details.

  • Thanks @Diptarag - that pushed me in the right direction. I'll add the actual snippet that I used to your answer.
    – Johannes
    Oct 10, 2012 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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