我正在尝试从客户端Sharepoint网站下载文件。我正在使用sharepoint CSOM。
我的代码如下:
using Microsoft.SharePoint.Client;
var username = "username";
var password = "pass";
var url = "https://myclient.sharepoint.com/";
var fileurl = "https://myclient.sharepoint.com/teams/folder1/folder%20x/somefile.docx";
using (ClientContext context = new ClientContext(url))
{
SecureString passWord = new SecureString();
foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(username, passWord);
Uri filename = new Uri(fileurl);
string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
string serverrelative = filename.AbsolutePath;
Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(serverrelative);
context.Load(file);
ClientResult<Stream> streamResult = file.OpenBinaryStream();
context.ExecuteQuery();
var file2 = streamResult.Value;
}
问题是我的访问被拒绝,但是当我使用相同的凭据登录时,我可以成功下载文件。
更新
已确认这与文件夹或文件名中的空格无关。
答案 0 :(得分:0)
如果SharePoint网站使用multiple authentication providers using a set of Windows credentials(也与SharePoint Online相关),则附加标头必须包含在请求中:X-FORMS_BASED_AUTH_ACCEPTED
,其值为f
对于ClientContext
class,标题可以这样包含:
ctx.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.WebRequest.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f";
};
示例
var file = ctx.Web.GetFileByUrl(fileAbsUrl);
ctx.Load(file);
var streamResult = file.OpenBinaryStream();
ctx.ExecuteQuery();
//save into file
using (var fileStream = System.IO.File.Create(@"C:\path\filename.docx"))
{
streamResult.Value.Seek(0, SeekOrigin.Begin);
streamResult.Value.CopyTo(fileStream);
}
注意:使用
,而不是转换为相对网址GetFileByUrl
method可以接受绝对网址
答案 1 :(得分:0)
问题是我没有连接到正确的URL(新的ClientContext(URL))