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))
{
//...
}
}