简体   繁体   中英

How to check if file exist in sharepoint online?

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

Below code try to download file wich I dont 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 I can check if file exists without downloading it.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM