7

Is there any way other than looping through the Files to check whether the folder or files exist in document library using clientcontext - client object model.. Can someone confirm me whether the below code will work or not. Or will it create any exception??

using(var clientContext = new ClientContext(site)) 
{ 
Web web = clientContext.Web; 
Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl("/site/doclib/folder/filename.ext"); 
bool bExists = false; 
try { clientContext.Load(file); 
clientContext.ExecuteQuery(); 
 bExists = file.Exists; 
} catch{ } 
if (bExists ) { . . 
}

5 Answers 5

12

The following extension method demonstrates how determine whether file exist or not:

using Microsoft.SharePoint.Client;

namespace SharePoint.Client.Extensions
{
    public static class WebExtensions
    {
        public static bool TryGetFileByServerRelativeUrl(this Web web, string serverRelativeUrl, out File file)
        {
            var ctx = web.Context;
            try
            {
                file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
                ctx.Load(file);
                ctx.ExecuteQuery();
                return true;
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                {
                    file = null;
                    return false;
                }
                throw;
            }
        }
    }
}

Key points:

If file does not exists the exception Microsoft.SharePoint.Client.ServerException is encountered, this approach demonstrates a reliable way to determine whether file exist or not

Usage

using(var ctx = GetContext(webUri, userName, password))
{
   File file;
   if (ctx.Web.TryGetFileByServerRelativeUrl( "/documents/SharePoint User Guide.docx", out file))
   {
     //...
   }
}
5
  • it throwed an error, GetContext is not existing Nov 2, 2016 at 7:44
  • 1
    @vignesh, GetContext is a custom method that basically returns the authenticated instance of ClientContext Nov 2, 2016 at 8:03
  • oh okay If you still have the function's code please do share it. Thanks Nov 2, 2016 at 8:13
  • Is the answer by @martind below not reliable? A quick test shows that it works and it seems to me that if you can do it without throwing an exception, it would be preferred.
    – Jeff
    Feb 5, 2019 at 15:00
  • @Jeff, indeed the answer seems to be correct one Feb 5, 2019 at 15:08
5

I've seen many references to file.Exists not working in CSOM but the problem is typically caused by trying to do context.Load(file). If the file doesn't exist you can't load the file so the test itself breaks the result.

The following code works, however.

var file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
web.Context.Load(file, f => f => f.Exists); // Only load the Exists property
web.Context.ExecuteQuery();
return file.Exists;
2
  • 1
    I am using SP2013 CSOM. I am unable to find the Folder.Exists method. Is there some particular assembly that I need to reference? Apr 8, 2020 at 14:30
  • I'm using PnP to target SharePoint Online; load only Exists property didn't work when using GetFolderByServerRelativeUrl, it's still thrown an error 'File Not Found.'.
    – Ariwibawa
    Oct 28, 2022 at 7:02
4

Checking by ServerErrorCode. Msdn link

//https://msdn.microsoft.com/en-us/library/dd930252%28v=office.12%29.aspx?f=255&MSPPError=-2147217396
private const int SPServerFileNotFoundExceptionErrorCode = -2147024894;

private bool TryGetFolderByRelativeUrl(Web web, string folderRelativePath, out SP.Folder folder)
{
    folder = null;

    try
    {
        folder = web.GetFolderByServerRelativeUrl(folderRelativePath);
        web.Context.Load(folder);
        web.Context.ExecuteQuery();
    }
    catch (SP.ServerException serverEx) when (serverEx.ServerErrorCode == SPServerFileNotFoundExceptionErrorCode)
    {
        return false;
    }

    return true;
}
4

Folder exists:

FolderCollection folders = list.RootFolder.Folders;

ctx.Load(folders, fl => fl.Include(ct => ct.Name)
.Where(ct => ct.Name == "MyFolder"));

ctx.ExecuteQuery();

return folders.Any();
0

Yeah. It will create exception. I have tried to run your code and got exception as file path is not valid! enter image description here

2
  • Okay. Can you suggest me the correct solution for that?? Nov 1, 2015 at 16:47
  • use try/catch .... that is already in your code Nov 1, 2015 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.