Download all document versions in SharePoint Online

SharePoint Online Document Libraries can store quite a few documents alongwith their versions. Versioning in Sharepoint enables you to store, track, and restore items in a list and files in a library as they are changed. When versioning is enabled in libraries, you can track and manage information as it evolves.

Some organizations retain multiple versions of their files for legal reasons or audit purposes. But at times there is a need to download all or few of the versioned files from these libraries.

The following code sample allows you to download all the versions of a file from a SharePoint document library. The code uses CSOM (Client Side Object model); however the same approach can be extended for Powershell, JSOM (JavaScript object model) or any other if you prefer.

using System;
using System.IO;
using System.Security;
using Microsoft.SharePoint.Client;
 
namespace ConsoleApplication1
{
    public static class DownloadFileVersions
    {
        private const string DownloadLocation = @"C:\Downloads\";
        private const string SiteUrl = "https://yoursite/sites/demo/";
        private const string FileUrl = "/sites/demo/Lib/Document.docx";
 
        private static void Main()
        {
            using (var clientContext = new ClientContext(SiteUrl))
            {                
                var web = clientContext.Web;
                var file = web.GetFileByServerRelativeUrl(FileUrl);
                var versions = file.Versions;
                clientContext.Load(versions);
                clientContext.ExecuteQuery();
 
                if (versions != null)
                {
                    foreach (var oldFileVersion in versions)
                    {
                        // Add version label to file in format: [Filename]_v[version#].[extension]
                        var filename = $"{Path.GetFileNameWithoutExtension(oldFileVersion.Url)}_v{oldFileVersion.VersionLabel}{Path.GetExtension(oldFileVersion.Url)}";
                        var downloadPath = Path.Combine(DownloadLocation + filename);
                        var str = oldFileVersion.OpenBinaryStream();
                        clientContext.ExecuteQuery();
                        using (var fs = new FileStream(downloadPath, FileMode.OpenOrCreate))
                        {
                            str.Value.CopyTo(fs);
                        }
                    }
                }
 
                Console.WriteLine("All File Versions Downloaded Sucessfully!!");
                Console.ReadLine();
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *