1

I have created a function using the SharePoint CSOM to extract all files within a Document Collection (List) using the below code however it takes over 5 minutes to get a list of 3671 files.

Is it possible to speed this up and if so How? I've seen other people use CAML Queries to extract files from a folder although I'm not 100% sure on how I would implement that.

    static SharePointOnlineCredentials SPCreds = new SharePointOnlineCredentials("*********", new System.Net.NetworkCredential("", "*******").SecurePassword);
    static string sharepointURL = "https://********";
    static string ListName = "Documents";
    static string docuemntsStartWith = "Shared Documents";

    static List<string> files = new List<string>();

    static void Main(string[] args)
    {
        using (ClientContext clientContext = new ClientContext(sharepointURL))
        {
            clientContext.Credentials = SPCreds;
            List list = clientContext.Web.Lists.GetByTitle(ListName);                
            clientContext.Load(list);
            getFilesInFolder(clientContext, list.RootFolder);
        }
        Console.WriteLine("Extracted all " + files.Count + " files");
        Console.Read();
        foreach(string f in files)
        {
            Console.WriteLine(f);
        }
        Console.WriteLine("DONE");

        Console.Read();
    }

    public static void getFilesInFolder(ClientContext cc, SP.Folder SPFolder)
    {
        cc.Load(SPFolder);
        cc.Load(SPFolder.Folders);
        cc.Load(SPFolder.Files);
        cc.ExecuteQuery();
        FolderCollection fcol = SPFolder.Folders;
        FileCollection filecol = SPFolder.Files;
        foreach (SP.File SPF in filecol)
        {
            files.Add(SPF.ServerRelativeUrl);
        }

        foreach (SP.Folder SPF in fcol)
        {
            getFilesInFolder(cc, SPF);
        }
    }
1

Since you only need the urls of the files, and not the content, you can use the following code for your getFilesInFolder method and it should do the trick:

public static void getFilesInFolder(List list)
{
    CamlQuery query = CamlQuery.CreateAllItemsQuery();
    query.ViewXml   = "<View Scope=\"Recursive\"><Query><Where><Eq><FieldRef Name=\"FSObjType\" /><Value Type=\"Number\">0</Value></Eq></Where></Query></View>";

    var items = list.GetItems(query);
    list.Context.Load(items);
    list.Context.ExecuteQuery();

    foreach (var SPF in items)
    {
        files.Add(SPF.FieldValues["FileRef"].ToString());
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.