我有一个winforms应用程序,我需要从Sharepoint OneDrive目录下载文件。目前,根据我的代码,我可以阅读文件标题,但我无法找到任何帮助我使用 Microsoft.SharePoint.Client 下载代码的内容。
string username = "appuser@abcuseraccount.com";
String pwd = "x!@ex";
ClientContext context = new ClientContext("https://abcuser.sharepoint.com/Main/financial/");
SecureString password = new SecureString();
foreach (char c in pwd.ToCharArray())
{
password.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, password);
context.ExecuteQuery();
List docs = context.Web.Lists.GetByTitle("Financial Notes");
Web site = context.Web;
context.Load(site);
context.ExecuteQuery();
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
ListItemCollection items = docs.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
MessageBox.Show(listItem["Title"].ToString());
}
如何将文件下载到本地驱动器(不使用LiveAccount身份验证)?
答案 0 :(得分:1)
使用File.OpenBinaryDirect method从SharePoint网站下载指定的文件。
以下示例演示了如何通过提供项目ID来从库中下载文件。
实施例
/// <summary>
/// Download file from a Library
/// </summary>
/// <param name="context">CSOM context</param>
/// <param name="listTitle">List Title</param>
/// <param name="listItemId">List Item Id</param>
/// <param name="downloadPath">Download Path</param>
private static void DownloadFile(ClientContext context, string listTitle, int listItemId, string downloadPath)
{
var list = context.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
context.Load(listItem, i => i.File);
context.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);
var fileName = Path.Combine(downloadPath, listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}