Below code is to check if the folder already exists in a SharePoint List.
private void CreateFolderInList(string folderName, string listName, SPListCollection listCollection)
{
try
{
//Creating folder in "Sites" Lists
SPList list = listCollection[listName];
//Check if the Folder is already available in the list
SPQuery query = new SPQuery();
query.Query = "<Where><And><Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq><Eq><FieldRef Name=’FSObjType’/><Value Type=’Lookup’>1</Value></Eq></And></Where>";
query.ViewAttributes = "Scope=\"RecursiveAll\""
//Retrieve the items based on Query
SPListItemCollection items = list.GetItems(query);
//Item count is "0" if the folder does not exist
if (items.Count == 0)
{
folderItem = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);
folderItem["Title"] = folderName;
folderItem.Update();
//return folderItem.Url;
}
}
catch (Exception ex)
{
}
}
Doesn't the SPQuery that checks for existence return normal list items as well and not just folders?
ReplyDeleteCheers,
Christian Fredh
http://www.christianfredh.com/blog/
Yes, the earlier code does populate all the items. But now I've updated the code, so that it will just populate the folder. Thanks Christian for the pointer.
ReplyDeletePrasath,
ReplyDeleteWhat namespaces should be inherited for this code to work?
Microsoft.SharePoint
Delete