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

问题描述 投票:1回答:1

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

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

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

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

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

c# visual-studio-2013 sharepoint-2010 sharepoint-2013
1个回答
5
投票

如果您未在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("[email protected]", 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:\temp
    using (var fileStream = 
        new FileStream(@"c:\temp\" + 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.