Get a list of files from Sharepoint and download the latest file

23.7k Views Asked by At

I am trying to get a list of files from a SharePoint location and then get the latest (by creation time) file using C#.

The resources available talk about SPWeb/SPSite but these are not available directly on Visual Studio 2013;

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

So far I have been unable to do so.

Could anyone please provide some useful resource or examples?

1

There are 1 best solutions below

2
On

If you're not running your code on the SharePoint server then you'll need to use the Client Object Model.

Complete basic operations using SharePoint 2013 client library code

I believe this should run against SharePoint as long as you have access to the url. I ran this against my Office 365 and that works. I have to authenticate agains Office 365 but you might be able to skip that if your AD user has permissions to access the library.

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);
}

And the extension to save the stream taken from 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);
}