Based on the doc from MS https://docs.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?
1 Answers
2
votes
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();