4

Based on the doc from MS https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/using-csom-for-dotnet-standard, Save/OpenBinaryDirect methods is not available for .NET core app, they suggest to use regular file API, so what is the alternative way to read/write files stored in SharePoint online? what is the regular file API? does anyone done this? any example code/documentation?

enter image description here

10031103
  • 83
  • 1
  • 7

2 Answers2

6

Download file in .NET Core CSOM:

  using (var authenticationManager = new AuthenticationManager())
  using (var context = authenticationManager.GetContext(site, user, password))
  {
    context.Load(context.Web, p => p.Title);
    context.ExecuteQuery();
    Microsoft.SharePoint.Client.File file = context.Web.GetFileByUrl("https://tenant.sharepoint.com/sites/michael/Shared%20Documents/aa.txt");
    context.Load(file);
    context.ExecuteQuery();       
    string filepath = @"C:\temp\" + file.Name;



    Microsoft.SharePoint.Client.ClientResult<Stream> mstream = file.OpenBinaryStream();
    context.ExecuteQuery();
    
    using (var fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Create))
    {
      mstream.Value.CopyTo(fileStream);
    }


    using (System.IO.StreamReader sr = new System.IO.StreamReader(mstream.Value))
    {
      String line = sr.ReadToEnd();
      Console.WriteLine(line);
    }

  }

Upload file in .NET Core CSOM:

string filepath = @"C:\temp\aa.txt";
FileCreationInformation newfile = new FileCreationInformation();
newfile.Url = System.IO.Path.GetFileName(filepath);
newfile.Content= System.IO.File.ReadAllBytes(filepath);

List library = context.Web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = library.RootFolder.Files.Add(newfile);
context.Load(uploadFile);
context.ExecuteQuery();
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Jerry
  • 3,480
  • 1
  • 10
  • 12
1

Jerry's answer got me there, but I wanted to add a couple of extras that weren't mentioned in his answer.

If your file destination isn't the main Documents list, instead of the Lists.GetByTitle call use

var folder = context.Web.GetFolderByServerRelativeUrl(...);
File uploadFile = folder.Files.Add(newfile);

If you're updating a file, you've got to set

newFile.Overwrite = true;

And if the file you're uploading/replacing is greater than 2MB, you've got to use the ContentStream instead of Content

FileCreationInformation newfile = new FileCreationInformation
{
    Url = relativeUrl,
    ContentStream = stream,
    Overwrite = true
};
chris84948
  • 3,940
  • 3
  • 22
  • 25