views:

326

answers:

1

I have a List which has a two level hierarchy of folders. Something like this:

List
    Folder_1
       SubFolder_1
              Item 1_1_1
              Item 1_1_2
       SubFolder_2
              Item 1_2_1
              Item 1_2_2
              Item 1_2_3
    Folder_2
       SubFolder_1
              Item 2_1_1
              Item 2_1_2
              Item 2_1_3
       SubFolder_2
              Item 2_2_1
              Item 2_2_2

I want to add a list item to a folder depending on some criteria. I don't want to loop through all folders as the number of folders is more. So, I thought of running a CAML query to get the folder.

Below CAML Query gives me all folders in the list:

<Where>
    <Eq>
        <FieldRef Name='FSObjType' />
        <Value Type='int'>0</Value>
    </Eq>
</Where>

How can I add another condition to the above query so that I can get a specific folder when I know the exact folder name?

A: 

You could try using FileLeafRef or FileDirRef as the name. I don't think that will work, though, as you need an SPFolder object to add a list Item to it and CAML queries return SPListItemCollection. Check out http://msdn.microsoft.com/en-us/library/bb862315.aspx for a list of some fieldnames you could try.

Since you know the name (and I presume the whole path) of the folder, why don't you use the SPWeb.GetFolder method to get the folder and then add an item using that folder object?

The following two links might be useful:

A snippet from the second link:

Creating a SPListItem in a SPFolder Using the OM

Creating a folder (SPFolder) using the WSS 3.0 object model is simple. Creating a list item (SPListItem) in a list is simple as well. It took me awhile and a number of emails to finally create a list item in an existing folder. So here is the code to save you some time.

SPSite site = new SPSite("http://[ServerName/sitename]"); 
SPWeb web = site.OpenWeb(); 
SPList list = web.Lists["Tasks"]; 

SPFolder f = web.GetFolder("http://[ServerName/sitename]/Lists/Tasks/Test" );
if(f.Exists)
{
   SPListItemCollection itemColl = list.Items;

   SPListItem item = itemColl.Add(f.ServerRelativeUrl, 
                                  SPFileSystemObjectType.File,
                                  null);

   item["Title"] = "Added from OM";
   item.Update();
}

If you are uploading a file, the first link will be useful. If it is just a plain list item, the second link (and the code I pasted here) might be useful.

Good luck!

Moron