开发者

How to get a folder from CAML Query?

开发者 https://www.devze.com 2023-01-01 11:53 出处:网络
I have a List which has a two level hierarchy of folders. Something like this: List Folder_1 SubFolder_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>
    <开发者_JAVA技巧;/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?


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:

  • http://stsadm.blogspot.com/2007/12/add-list-item.html

  • http://darrinbishop.com/blog/archive/2007/04/08/41.aspx

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消