Search code examples
c#sharepointoffice365csom

C# CSOM - Check if File Exists in Document Library


I'm coding in C# using CSOM, my app uploads a template asp.net page to the "/Pages/" library, I need it to check if a file exists in that location with the same name prior to file upload (then maybe it can return a bool value).

I did have a quick look but the majority of the solutions I found referred to the use of Javascript, or applied to on-prem deployments.

If someone could please point me in the right direction I would appreciate it.


Solution

  • You could consider the following approaches to determine whether file exists or not.

    Query based

    You could construct CAML query to find list item by its Url as demonstrated below:

    public static bool FileExists(List list, string fileUrl)
    {
        var ctx = list.Context;
        var qry = new CamlQuery();
        qry.ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FileRef\"/><Value Type=\"Url\">{0}</Value></Eq></Where></Query></View>",fileUrl);
        var items = list.GetItems(qry);
        ctx.Load(items);
        ctx.ExecuteQuery();
        return items.Count > 0;
    }
    

    Usage

    using (var ctx = GetSPOContext(webUri,userName,password))
    {
         var list = ctx.Web.Lists.GetByTitle(listTitle);
         if(FileExists(list,"/documents/SharePoint User Guide.docx"))
         {
              //...
         }
    }
    

    Web.GetFileByServerRelativeUrl Method

    Use Web.GetFileByServerRelativeUrl Method to return the file object located at the specified server-relative URL.

    If file does not exists the exception Microsoft.SharePoint.Client.ServerException will be encountered:

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

    Usage:

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