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

Kev*_*vin 1 c# sharepoint-2010 sharepoint-2013 visual-studio-2013

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

可用资源讨论了SPWeb / SPSite,但这些资源在Visual Studio 2013上不直接可用;请参见参考资料。

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

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

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

Gun*_*rsi 5

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

使用SharePoint 2013客户端库代码完成基本操作

我相信,只要您有权访问URL,它就应该针对SharePoint运行。我在Office 365上运行了它,并且可以正常工作。我必须再次验证Office 365,但如果您的AD用户具有访问该库的权限,则您可以跳过该验证。

SharePoint 2013:在Office 365中验证.NET客户端对象模型

// 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:\temp
    using (var fileStream = 
        new FileStream(@"c:\temp\" + fileInfo.File.Name, FileMode.Create))
        fileInformation.Stream.CopyTo(fileStream);
}
Run Code Online (Sandbox Code Playgroud)

和扩展来保存从这里获取的流

// 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);
}
Run Code Online (Sandbox Code Playgroud)