Is there a way other than looping through the Files in a SPFolder to determine if a give filename (string) exists?
Asked
Active
Viewed 5.3k times
3 Answers
30
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.

Lars Fastrup
- 5,458
- 4
- 31
- 35
10
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 )
{
.
.
}
}
-
The exception is typically caused by trying to do context.Load(file). If the file doesn't exist you can't load the full object so the test itself breaks the result. The exception won't be thrown if you replace clientContext.Load(file) with clientContext.Load(file, f => f.Exists). – Martin D Jan 24 '17 at 20:20
1
Using a CAML query is the most efficient way (example here)
CAML can be a bit unwieldy, so also worth looking at the Linq to Sharepoint provider, which hides the details of CAML away from you.

Paul Nearney
- 6,965
- 2
- 30
- 37