April 20, 2024

SamTech 365

PowerPlatform, Power Apps, Power Automate, PVA, SharePoint, C#, .Net, SQL, Azure News, Tips ….etc

Check if a file exist with C# using SharePoint Client Object Modal

Hi Guys, if you need  to test using C# if a file exist in a certain SharePoint document library ? You can use SharePoint Client Object Modal.
Here, I wrote a C# console application which uses behind the scene the built in SharePoint web services.
using System;
using Microsoft.SharePoint.Client;
 
namespace TestExist
{
    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;
            }
        }
    }
}
 
1