Sharepoint - How to check if the file or folder exist in SharePoint document library using client object model?

The following extension method demonstrates how determine whether file exist or not:

using Microsoft.SharePoint.Client;

namespace SharePoint.Client.Extensions
{
    public static class WebExtensions
    {
        public static bool TryGetFileByServerRelativeUrl(this Web web, string serverRelativeUrl, out File file)
        {
            var ctx = web.Context;
            try
            {
                file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
                ctx.Load(file);
                ctx.ExecuteQuery();
                return true;
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                {
                    file = null;
                    return false;
                }
                throw;
            }
        }
    }
}

Key points:

If file does not exists the exception Microsoft.SharePoint.Client.ServerException is encountered, this approach demonstrates a reliable way to determine whether file exist or not

Usage

using(var ctx = GetContext(webUri, userName, password))
{
   File file;
   if (ctx.Web.TryGetFileByServerRelativeUrl( "/documents/SharePoint User Guide.docx", out file))
   {
     //...
   }
}

I've seen many references to file.Exists not working in CSOM but the problem is typically caused by trying to do context.Load(file). If the file doesn't exist you can't load the file so the test itself breaks the result.

The following code works, however.

var file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
web.Context.Load(file, f => f => f.Exists); // Only load the Exists property
web.Context.ExecuteQuery();
return file.Exists;

Folder exists:

FolderCollection folders = list.RootFolder.Folders;

ctx.Load(folders, fl => fl.Include(ct => ct.Name)
.Where(ct => ct.Name == "MyFolder"));

ctx.ExecuteQuery();

return folders.Any();

Tags:

Csom