September 28, 2022

Samir Daoudi's Technical Blog

SharePoint, Office 365, C#, .Net, SQL Server News, Tips, Ebooks, Events, Webinars ….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;
            }
        }
    }
}
 

Leave a comment

You may have missed

Show Buttons
Hide Buttons

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

%d bloggers like this: