Alternative Save/OpenBinaryDirect methods for CSOM for SharePoint Online

谁说胖子不能爱 提交于 2021-01-29 14:31:23

问题


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:


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();


来源:https://stackoverflow.com/questions/62918952/alternative-save-openbinarydirect-methods-for-csom-for-sharepoint-online

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!