How to check if file exists in SharePoint online?

1.1k Views Asked by At

I'm working with SharePoint online and using code I need to check if file exists or not. Please don't I don't need to download file. My code will use its URL if file exist so no need to download it.

Below code tries to download file which I don't want:

class Program
{
    static void Main(string[] args)
    {
        string Web = @”https://domain/sitecollection/“;
        string FileName = @”/Sitecollection/Records/file.txt”;
        
        ClientContext clientContext = new ClientContext(Web);
        Web site = clientContext.Web;

        if (TryGetFileByServerRelativeUrl(site, FileName)) Console.WriteLine(“File exists”); elseConsole.WriteLine(“File does not exist”);
        Console.ReadLine();
    }

    public static bool TryGetFileByServerRelativeUrl(Web web, string serverRelativeUrl)
    {
        var ctx = web.Context;
        try
        {
            File file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
            ctx.Load(file);
            ctx.ExecuteQuery();
            return true;
        }
        catch (Microsoft.SharePoint.Client.ServerException ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex.Message);
            if (ex.ServerErrorTypeName == “System.IO.FileNotFoundException”)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                return false;
            }
            return false;
        }
        catch (Exception exp)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(exp.Message);
            return false;
        }
    }
}

Please help how can I check if a file exists without downloading it.

1

There are 1 best solutions below

2
On BEST ANSWER

Use CAML query to query based on file url.

    var query = new CamlQuery();
    query.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(query);
    ctx.Load(items);
    ctx.ExecuteQuery();
    return items.Count > 0;