c# - 如何使用 C# 在 SharePoint Online 中读取单个文件的内容
问题描述
我有以下 url,它在放入浏览器时显示文件的元数据,但我想要实际的文件内容。
https://mySite/_api/web/folders/getbyurl('Shared%20Documents')/folders/getbyurl('09.%20SharePoint%20Tutorials')/files/GetByUrl('SharePoint%20365%20Co-authoring%20excel%20files.docx')
我尝试执行以下操作,但尝试在第 4 行执行查询时出现 400 错误:
ClientContext clientContext = new ClientContext("mySite");
File f = clientContext.Web.Folders.GetByUrl("Shared Documents").Folders.GetByUrl("09. SharePoint Tutorials").Files.GetByUrl("SharePoint 365 Co-authoring excel files.docx");
clientContext.Load(f);
clientContext.ExecuteQuery();
FileInformation fileInformation = File.OpenBinaryDirect(clientContext, (string)f.ServerRelativeUrl);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
解决方案
下面的代码供您参考:
string targetSiteURL = @"https://xx.sharepoint.com/sites/lz";
var login = "lz@xxx.onmicrosoft.com";
var password = "xxx";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
ClientContext ctx = new ClientContext(targetSiteURL);
ctx.Credentials = onlineCredentials;
var web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
var filePath = web.ServerRelativeUrl + "/Shared%20Documents/09.%20SharePoint%20Tutorials/SharePoint%20365%20Co-authoring%20excel%20files.docx";
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, filePath);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
Console.ReadKey();
推荐阅读
- javascript - 如何只使用一个到 MongoDB 的连接?
- angularjs - 您如何通过对象的对象进行 ng-repeat 以显示键和值?
- ansible - 在 Ansible 中为每个环境分配变量的问题
- node.js - knex Adonis 查询:事务查询已完成
- html - 导航在背景 img 之上
- python-3.x - Python .txt 文件无法正确读取
- django - 从 ManyToManyField 填充 MultipleChoiceField 值
- python - 如何在同一行打印这些字符?
- python - 将单词传递给函数
- c# - `Clicked` 和 `Command` 在同一个 Xamarin 视图上使用时如何工作?