Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a file exists in a SharePoint SPFolder [closed]

Tags:

sharepoint

Is there a way other than looping through the Files in a SPFolder to determine if a give filename (string) exists?

like image 669
Chris Woodruff Avatar asked Dec 11 '08 15:12

Chris Woodruff


People also ask

What does it mean when a document is checked out in SharePoint?

When you check out a document, users will still be able to access the latest version of the document in SharePoint document library, but only in Read mode. They will not be able to make any edits or save the document back to the library until the original document is checked back in.

How do I find out what folder a document is in in SharePoint?

SharePoint files can be access via a web URL. So to find that URL you can open the browser, then type the SharePoint site url. Then choose the library/folder you uploaded the file. Then you can right click the file and copy the URL.


2 Answers

You can, if you know the URL also use the SPFile.Exists property as follows:

using (SPSite site = new SPSite("http://server/site"))
using (SPWeb web = site.OpenWeb())
{
  SPFile file = web.GetFile("/site/doclib/folder/filename.ext");
  if (file.Exists)
  {
    ...
  }
}

One would on first thought assume SPWeb.GetFile throws an exception if the file does not exist. But as you see this is not the case - it will actually return a SPFile object.

like image 85
Lars Fastrup Avatar answered Sep 25 '22 07:09

Lars Fastrup


But if you are using SP 2010 Client OM, it would actually throw an exception if the file doesn't exist:

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(); //Raises exception if the file doesn't exist
         bExists = file.Exists;  //may not be needed - here for good measure
     }
     catch{   }

     if (bExists )
     {
           .
           .
     }
}
like image 38
Ben Avatar answered Sep 24 '22 07:09

Ben