Sharepoint 2013 Check If File Already Exists In Document Library Using CSOM

SharePoint 2013 supports API methods given below to perform basic operations like Create, Update, Read and Delete .
  • Server Side Object Model (SSOM).
  • Client Object Model (CSOM).
  • JavaScript Object Model (JSOM).
  • REST.
Server Side Object Model is pure .NET code but here, one needs to use Client Object Model to perform all the basic operations in SharePoint 2013 to achieve all this.
Prerequisites to perform these operations are given below.
  • Visual Studio 2012.
  • SharePoint 2013.
Before starting to develop the code, we have to add DLL assembly reference.
  • SharePoint.Client.Runtime.dll.
  • SharePoint.Client.dll.
Add the line given below in your namespace.

using Microsoft.SharePoint.Client;

Now, we are going to see how to create a list in SharePoint 2013 programmatically.

Use Web.GetFileByServerRelativeUrl Method to return the file object located at the specified Server-relative URL. 

Code 
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text.RegularExpressions;    
  5. using Microsoft.SharePoint.Client;    
  6. namespace Rextester {    
  7.     public class Program {    
  8.         public static void Main(string[] args) {    
  9.             ClientContext context = new ClientContext("http://gowtham.sharepoint.com");    
  10.             Web web = context.Web;    
  11.             Microsoft.SharePoint.Client.File file;  
  12.               if(TryGetFileByServerRelativeUrl(Web,"/documents/test.docx",out file))  
  13.               {  
  14.                   //File Already Exists  
  15.               }  
  16.         }    
  17.     }    
  18.       
  19.     public static bool TryGetFileByServerRelativeUrl(Web web, string serverRelativeUrl,out Microsoft.SharePoint.Client.File file)  
  20.     {  
  21.         var ctx = web.Context;  
  22.         try{  
  23.             file = web.GetFileByServerRelativeUrl(serverRelativeUrl);  
  24.             ctx.Load(file);  
  25.             ctx.ExecuteQuery();  
  26.             return true;  
  27.         }  
  28.         catch(Microsoft.SharePoint.Client.ServerException ex){  
  29.             if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")  
  30.             {  
  31.                 file = null;  
  32.                 return false;  
  33.             }  
  34.             else  
  35.                 throw;  
  36.         }  
  37.     }  
  38. }      
Conclusion

Was my blog helpful? If yes, please let me know and if not, please explain what was confusing or missing.

I’ll use your feedback to double-check the facts, add info and update this blog.