C# 获取sharepoint列表的所有项目
我想下载sharepoint列表中的所有文件。 我使用以下方法下载文件:C# 获取sharepoint列表的所有项目,c#,sharepoint,directory,subdirectory,sharepoint-clientobject,C#,Sharepoint,Directory,Subdirectory,Sharepoint Clientobject,我想下载sharepoint列表中的所有文件。 我使用以下方法下载文件: public void DownloadFilesOfSpecialtys( ) { using (var clientContext = new ClientContext(url)) { foreach (var item in ids) { int l
public void DownloadFilesOfSpecialtys( )
{
using (var clientContext = new ClientContext(url))
{
foreach (var item in ids)
{
int listItemId = int.Parse(item.ToString());
statics.files = int.Parse(ids.Count.ToString());
var list = clientContext.Web.Lists.GetByTitle(listtitle);
var listItem = list.GetItemById(listItemId);
clientContext.Load(list);
clientContext.Load(listItem, i => i.File);
clientContext.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
var fileName = Path.Combine(@path , (string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
}
}
现在我的问题是,子文件夹中的文件不是用这种方法下载的。
是否有机会浏览“我的列表”中的所有子文件夹并下载所有文件?当您拥有listItem对象时,它可能已经是文件夹,因此您可以使用.folder属性将其视为文件夹:
var listItemAsFolder = listItem.Folder;
if (listItemAsFolder != null) {
// here you can access listItemAsFolder.Files to get all files in the folder
// also, you can access listItemAsFolder.SubFolders to get all subfolders.
}
顺便说一句,还有一种方法:当您有一个SPFolder对象时,使用.Item将其视为列表项。因为您的目标是:
下载我的SharePoint列表的所有文件
以下示例演示了如何完成此任务:
using (var ctx = new ClientContext(webUri))
{
var qry = new CamlQuery();
qry.ViewXml = "<View Scope='RecursiveAll'>" +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='FSObjType' />" +
"<Value Type='Integer'>0</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>";
var sourceList = ctx.Web.Lists.GetByTitle(sourceListTitle);
var items = sourceList.GetItems(qry);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (var item in items)
{
//1. ensure target directory exists
var curPath = targetPath + System.IO.Path.GetDirectoryName((string)item["FileRef"]);
Directory.CreateDirectory(curPath);
//2. download a file
DownloadAFile(item, curPath);
}
}
注意:与SharePoint 2010/2013 CSOM API兼容
作为奖励,一旦文件被删除,文件夹结构将被保留
下载
listItemAsFolder.SubFolder在我的案例中不存在它的子文件夹(带s),它是Folder的所有子文件夹的集合Yeah我写它的子文件夹为false sry,不可用任何其他对象,您必须首先在上下文中加载它们:var folders=listItemAsFolder.SubFolders;加载(文件夹)@LInsoDeTeh,根本不需要检查对象类型,只需要构造正确的查询。除ListItem外,文件夹属性仅在2013 CSOM API中可用
private static void DownloadAFile(Microsoft.SharePoint.Client.ListItem item,string targetPath)
{
var ctx = (ClientContext)item.Context;
var fileRef = (string)item["FileRef"];
var fileName = System.IO.Path.GetFileName(fileRef);
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var filePath = Path.Combine(targetPath, fileName);
using (var fileStream = System.IO.File.Create(filePath))
{
fileInfo.Stream.CopyTo(fileStream);
}
}