从Sharepoint获取文件列表并下载最新文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Sharepoint获取文件列表并下载最新文件相关的知识,希望对你有一定的参考价值。

我试图从SharePoint位置获取文件列表,然后使用C#获取最新(按创建时间)文件。

可用资源谈论SPWeb / SPSite,但这些资源不能直接在Visual Studio 2013上使用;

SharePoint站点:https://sharepoint.amr.<Website>.com/sites/OrganizationName/Group/Shared Documents/Reports/Area/

到目前为止,我一直无法这样做。

有人可以提供一些有用的资源或例子吗?

答案

如果您未在SharePoint服务器上运行代码,则需要使用客户端对象模型。

Complete basic operations using SharePoint 2013 client library code

我相信只要您有权访问该网址,就应该针对SharePoint运行。我在Office 365上运行此功能。我必须再次对Office 365进行身份验证,但如果您的AD用户有权访问该库,则可以跳过该操作。

SharePoint 2013: Authenticating .NET Client Object Model in Office 365

// Url to site
string url = "https://your.sharepoint.com";
// get context for that Url
var ctx = new ClientContext(url);

// Provide credentials 
// (Might be able to skip this if the server is on prem and your 
// AD user has permissions to access the library)
var password = new SecureString();
foreach (var c in "your_password".ToCharArray())
    password.AppendChar(c);
ctx.Credentials = 
    new SharePointOnlineCredentials("login@your.onmicrosoft.com", password);

// get the library
var list = ctx.Web.GetList("/Shared%20Documents/");

// Empty query to get all items
var listItems = list.GetItems(new CamlQuery());

// Load all items and use Include to specify what properties
// we want to be able to access
ctx.Load(listItems, 
    items => items.Include(
        item => item["Created"], 
        item => item.File));
// Execute the query
ctx.ExecuteQuery();

// Just to show you we have all the items now
foreach (var item in listItems)
{
    Console.WriteLine("{0} - {1}", 
            item["Created"], 
            item.File.ServerRelativeUrl);
}

// Orderby something and take one
var fileInfo = listItems
    .OrderBy(x => x.File.Name)
    .Take(1)
    .FirstOrDefault();
if (fileInfo != null)
{
    // Open file
    var fileInformation = 
        File.OpenBinaryDirect(ctx, fileInfo.File.ServerRelativeUrl);

    // Save File to c:	emp
    using (var fileStream = 
        new FileStream(@"c:	emp" + fileInfo.File.Name, FileMode.Create))
        fileInformation.Stream.CopyTo(fileStream);
}

以及保存从here获取的流的扩展

// Extension to save stream
public static void CopyTo(this System.IO.Stream src, System.IO.Stream dest)
{
    if (src == null)
        throw new System.ArgumentNullException("src");
    if (dest == null)
        throw new System.ArgumentNullException("dest");

    System.Diagnostics.Debug.Assert(src.CanRead, "src.CanRead");
    System.Diagnostics.Debug.Assert(dest.CanWrite, "dest.CanWrite");

    int readCount;
    var buffer = new byte[8192];
    while ((readCount = src.Read(buffer, 0, buffer.Length)) != 0)
        dest.Write(buffer, 0, readCount);
}

以上是关于从Sharepoint获取文件列表并下载最新文件的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Power Query 从 SharePoint 库中的(许多)文档中获取数据

使用 Web 服务从 SharePoint 下载文件的特定版本

sharepoint - 从多个网站的列表中获取项目

从 sharepoint 获取所有文档的列表

更新 AD 组内的 sharepoint 用户配置文件

从 SP 2010 文档库中获取文档的最新签入版本(文档)