4

I need to create several documents in my SharePoint Online library. I am using the following code to upload an existing file to a library:

            ctx.Load(ctx.Web.Folders);
            ctx.ExecuteQuery();

            ctx.Load(ctx.Web.Folders);
            ctx.ExecuteQuery();
            Folder myLibrary = ctx.Web.Folders.GetByUrl("Shared Documents");
            String fileName = System.IO.Path.GetFileName(fileToUpload);
            FileStream fileStream = System.IO.File.OpenRead(fileToUpload);
            FileCreationInformation fci = new FileCreationInformation();
            fci.Overwrite = false;
            fci.Url = "gg.txt";
            fci.ContentStream = fileStream;
            //byte[] docstream= {134,53,53,55,75,6,5};
            //fci.Content = docstream;
            Microsoft.SharePoint.Client.File spfile = myLibrary.Files.Add(fci);

            myLibrary.Update();
            ctx.ExecuteQuery();

However, all Office documents (.docx, .xlsx, .doc) seem to be corrupt and I cannot open them in Word/Excel Online after upload. No issues with .txt files.

I have been trying to use this, which would be perfect for me:
Create a Word Document in a document library programmatically

Microsoft.SharePoint.Client.File file 
                                  = docLib.RootFolder.Files.Add(fileName, memStream, true);

but SharePoint Online doesn't accept 3 arguments for .Add() function, only FileCreationInformation.

The questions:
1) How can I adapt Files.Add() for SharePoint Online? Is there a similar function that would allow me to pass in the content of the file?

2) Why are all my Office files corrupted?

3) I expected fci.Content to create a content inside the file. Apparently it's not the case, because it doesn't seem to do anything. What does it do?

3

Create a Document and then upload it into SharePoint Online library:

var fileName = @"SharePoint User Guide.docx";
var targetUrl = "/Shared Documents";

using (var stream = new MemoryStream())
{
    //1. Create Document
    using (var document = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
    {
        document.AddMainDocumentPart();
        document.MainDocumentPart.Document = new Document(new Body(new Paragraph(new Run(new Text("Some content goes here")))));                    
    }        

     //2. Upload file into SharePoint Library
     using (var ctx = new ClientContext(webUri))
     {
         ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
         var targetFileUrl = String.Format("{0}/{1}", targetUrl, fileName);
         stream.Position = 0;
         Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx,targetFileUrl , stream, true);
     }

 }

Key points

Result

enter image description here

  • It's working only for rootsite domain.sharepoint.com and not for any of the site collections. I don't get any errors(creation, connection, none), the code goes through all the commands and there is completely no result in the SPO library. Tested on 2 tenants with the same results. Will run more tests and keep you updated. – grisha Nov 24 '14 at 12:29
  • 1
    In that case please make sure the proper server relative url of Library is specified. For example: var targetUrl = "/site url/web/Documents"; – Vadim Gremyachev Nov 24 '14 at 20:09
  • Works :) I still have an error when opening those documents in Word Online:"sorry word online ran into a problem opening this document. To view this document...", which seems similar to my original issue :/ Error occurs regardless of the browser and doesn't appear for the files I upload manually. Tested also with Excel files SpreadsheetDocument.Create(...). The .doc and .xls extensions don't open at all. .docx and .xlsx give the error in Web Apps and open empty in local Office. If I open them locally and then save, they will be viewable/editable online later. – grisha Nov 25 '14 at 8:32
  • 1
    Just updated the answer (results section). It's hard to say why this error occurs in your case, but after running the script provided in answer i got this result – Vadim Gremyachev Nov 27 '14 at 21:47
  • 1
    Works, not sure why :) When I figure it out, I'll delete this comment and post a more useful one. Thank you, Vadim! – grisha Nov 28 '14 at 9:37
2

Here is a working example. Code looks mostly the same as yours except for the use of the Content property.

var web = context.Web;
var list = web.Lists.GetByTitle("Project Documents");

var filePath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) +
    @"\Samples\Sample01.docx";

var fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes(filePath);
fci.Url = "Sample01.docx";
fci.Overwrite = true;
var file = list.RootFolder.Files.Add(fci);

context.ExecuteQuery();

BTW, this example comes from my Client Object Model and REST API Development course on Pluralsight. You can get a free trial if you want to watch the section on uploading files.

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.