C# CSOM - Vérifier si un fichier existe dans une bibliothèque de documents

C# CSOM - Vérifier si un fichier existe dans une bibliothèque de documents


Source : Stack Overflow [office365]

Vous pourriez envisager les approches suivantes pour déterminer si un fichier existe ou non.

Basée sur une requête

Vous pourriez construire une requête CAML pour trouver un élément de liste par son URL comme démontré ci-dessous :

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;
}

Utilisation

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

Méthode Web.GetFileByServerRelativeUrl

Utilisez la méthode Web.GetFileByServerRelativeUrl pour retourner l’objet fichier situé à l’URL relative au serveur spécifiée.

Si le fichier n’existe pas, l’exception Microsoft.SharePoint.Client.ServerException sera rencontrée :

  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;
        }
    }

Utilisation :

 using (var ctx = GetSPOContext(webUri,userN

*(Réponse tronquée)*