Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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";
listItem.Update();
clientContext.ExecuteQuery();

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!

share|improve this question
add comment

1 Answer 1

up vote 0 down vote accepted

With C# you can do it this way -

SPFolder doclib = web.Folders["Document Library"];
web.AllowUnsafeUpdates=true; 
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);
clientContext.Load(file);
clientContext.ExecuteQuery();

Check this link for more details.

share|improve this answer
    
Thanks @Diptarag - that pushed me in the right direction. I'll add the actual snippet that I used to your answer. –  Jazzturtle Oct 10 '12 at 13:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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