Recently I wanted to use the SPQuery object to locate an item (file) from a document library by searching on the filename.
I came across the following intersting limitation when using the SPQuery.
SharePoint store the filename of an in a native field on SPListItem called "Name".
One would therefore assume the "Name" field can be used in SPQuery.
Lets start with an example of SPQuery which works.
The following code segment search for a SPListItem (File) based on the Title of the file.
Microsoft.SharePoint.SPQuery query = new SPQuery();
StringBuilder strQuery = new StringBuilder();
String strFileName;
strFileName = "LocateThisFile"; //Hard-coded for illustration
strQuery.Append("<Where><Eq><FieldRef name='Title'><Value Type='Text'>");
strQuery.Append(strFileName);
strQuery.Append("</Value></Eq></Where>");
query.Query = strQuery.ToString();
SPListItemCollection mylistitemcollection = null;
mylistitemcollection = mylistitem.ParentList.GetItems(query);
foreach( SPItem loopitem in mylistitemcollection)
{
loopitem.Delete();
break;
}
Now, one would assume that the same can be done, and that by replacing the "Title" field with "Name", one can search for the item by filename.
Lets try the following: (same code segment but "Title" replaced with "Name")
Microsoft.SharePoint.SPQuery query = new SPQuery();
StringBuilder strQuery = new StringBuilder();
String strFileName;
strFileName = "LocateThisFile.docx"; //Hard-coded for illustration
strQuery.Append("<Where><Eq><FieldRef name='Name'><Value Type='Text'>");
strQuery.Append(strFileName);
strQuery.Append("</Value></Eq></Where>");
query.Query = strQuery.ToString();
SPListItemCollection mylistitemcollection = null;
mylistitemcollection = mylistitem.ParentList.GetItems(query);
foreach( SPItem loopitem in mylistitemcollection)
{
loopitem.Delete();
break;
}
Unfortunately the code segment above does not work and an exception is raised. (similiar to when one provide an invalid field name / field does not exist in list definition).
So, I did the following as a work around. I know this is not very robust and will definitely be the wrong approach for large document libraries. I am still looking into the problem, but for now the code below works well. I will post an update as soon as I am able to get the SPQuery to work with the "Name" field.
SPListItemCollection items = rw.Lists[properties.ListId].Items;
for (int i = 0; i < items.Count; i++)
{
SPListItem looplistItem = items[i];
if (looplistItem["Name"].ToString() == strCheckSealedFileName)
{
looplistItem.Delete();
break;
}
}
Wednesday, December 23, 2009
Development Tip: C# Search for file in SharePoint document library using file name.
Subscribe to:
Post Comments (Atom)
2 comments:
Tech Intellectuals is a custom software development and staffing company. C# Development
Thank yoou for being you
Post a Comment