0

I have the following code that gets files from a document library. Works great for getting all the files. Now, however, I want to filter the files using the "title" param before passing it back to my MVC controller.

public IEnumerable<File> FindBy(string title, ClientContext clientContext)
{
    var documentLibrary = clientContext.Web.Lists.GetByTitle("Documents");
    clientContext.Load(documentLibrary);
    Folder folder = documentLibrary.RootFolder;
    clientContext.Load(folder);

    var files = folder.Files;
    clientContext.Load(files);
    clientContext.ExecuteQuery();
    return files;
}

Any ideas? I have tried using the

files.Select(x => x.files.Name.Contains(title))

Which turns it into an IQueryable<bool> but I can't get it back to the method's type of IEnumerable<File>

Any help is appreciated.

1

I found the solution to my problem. I changed my code to use the ListItemCollection instaed of FileCollection and used a CAML query to filter. Also, since I still need the File object (for the server relative Url), I loaded it in the context:

public IEnumerable<ListItem> FindBy(string fileName, ClientContext clientContext)
{
    var documentLibrary = clientContext.Web.Lists.GetByTitle("Documents");
    clientContext.Load(documentLibrary);

    CamlQuery query = new CamlQuery();
    query.ViewXml = @"<View><Query><Where><Contains><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + filename + @"</Value></Contains></Where></Query></View>";
    ListItemCollection listItems = documentLibrary.GetItems(query);
    clientContext.Load(listItems, includes => includes.Include(i => i["FileLeafRef"], i => i.File));

    clientContext.ExecuteQuery();
    return listItems;
}

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.