Check if file exists in list / library with CSOM

When you already know the full URL of the file you can use this code:

var web = clientContext.Web;
var file = web.GetFileByServerRelativeUrl(serverRelativeFileUrl);
var scope = new ConditionalScope(web.Context, () => !file.ServerObjectIsNull.Value && file.Exists);

using (scope.StartScope())
{
    web.Context.Load(file);
}
web.Context.ExecuteQuery();

if (scope.TestResult != null && scope.TestResult.Value)
{
    return true;
}

return false;

In the following example we check if a certain file (Item_TwoLines.js) is existing in the Master Page catalog with the usage of CAML.

var list = clientContext.Site.GetCatalog((int)ListTemplateType.MasterPageCatalog);
clientContext.Load(list);
clientContext.ExecuteQuery();

var query = new CamlQuery
{
      ViewXml = string.Format(
            CultureInfo.InvariantCulture,
            @"<View Scope='RecursiveAll'><QueryOptions><ViewAttributes Scope='Recursive' /></QueryOptions><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>{0}</Value></Eq></Where></Query></View>",
            "Item_TwoLines.js")
};

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

var item = items.FirstOrDefault();

When the item variable is not null, the item is existing. So should be the attached file.

The CAML statement also has some special settings. The Scope and the QueryOptions define that the query should be executed recursive in all sub folders. The Master Page catalog has some sub folders which will not be searched when using a standard CAML query.

It’s also possible to check the existence of a file by using the full file path. This is at least necessary when there are files with the same name but in different folders of the library. The file path is saved in the internal field column “FileRef”.

var query = new CamlQuery()
{
    ViewXml =
        string.Format(
            CultureInfo.InvariantCulture,
            @"<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileRef'/><Value Type='Url'>{0}</Value></Eq></Where></View></Query>",
            fileUrl)
};

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

var item = items.SingleOrDefault();

if (item == null)
{
    return false;
}

context.Load(item.File, f => f.Exists);
context.ExecuteQuery();

return item.File.Exists;

Leave a Reply

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

16 + 14 =