Tuesday, May 12, 2009

Check Record or FileName in a SPDocument Library

In this post I discussed how we can check whether a particular record / filename exist in a SPDocumentLibrary (SharePoint's document library) or not.

In the following method, first I discussed the 4 approaches suggested in following blog/forum, then the 5th apporach (in which I used SPQuery).

According to me the 5th and last approach is good-one because it would't raise an Exception.




/// <summary>
/// Check FileName/Records in SPDocumentLibrary
/// </summary>
void docLibFileExits()
{
SPWeb currentSite = SPContext.Current.Web;
SPDocumentLibrary docLib
= (SPDocumentLibrary)currentSite.GetList(currentSite.Url + "/Documents");

//APPROACH 1
if (docLib.RootFolder.Files[fileName] != null)
{
// do something
//This throws an Argument Exception
}

//APPROACH 2
if (docLib.RootFolder.Files[fileName].Exists == true)
{
// do something
//Again this throws a Argument Exception
}

//APPROACH 3
if (currentSite.GetFile(fileName).Exists == true)
{
// do something
//work
}

//APPROACH 4
bool fileExist = true;

try { docLib.RootFolder.Files[fileName]; }
catch (ArgumentException) { fileExist = false; }

if (fileExists)
{
//...
}



//APPROACH 5
SPSite oWebsite = SPContext.Current.Web;
SPList docLib = oWebsite.Lists["docLib"] as SPDocumentLibrary;
SPListItemCollection itemcolCVs = null;
SPQuery oQueryFileCheck = new SPQuery();

string FILENAME = ""; //FileName that you want to search.

//You can use EQUALS or CONTAINS operation as per your requirement.
//
/*
StringBuilder strBFileCheckQuery = new StringBuilder(
"<Where>" +
"<Eq>" +
"<FieldRef Name='FileLeafRef' />" +
"<Value Type='Text'>FILENAME</Value>" +
"</Eq>" +
"</Where>");
*/

StringBuilder strBFileCheckQuery = new StringBuilder(
"<Where>" +
"<Contains>" +
"<FieldRef Name='FileLeafRef' />" +
"<Value Type='Text'>FILENAME</Value>" +
"</Contains>" +
"</Where>");

oQueryFileCheck.Query = strBFileCheckQuery.ToString();
if (docLib.GetItems(oQueryFileCheck).Count > 0)
{
//To do
}

}





P.S. Here CAML Query Builder helped me a lot to identify and build above SPQuery.

2 comments:

Sudeep Ghatak said...

Thanks Avinash... This is exactly what I was looking for.

Pascal Van Vlaenderen said...

You're actually misusing the stringbuilder !!

You're concatinating the string when passing it to the constructor !

Use append to build the string.

Google