10

my problem is I have a document library with sub folders. Also the document library got more than one content type.

Is there a way to create a CAML or LINQ query to get all files of a certain content type from one of this sub folders.

The sub folder name is known.

Thanks in advance!

Markus S
  • 302
  • 1
  • 4
  • 12

2 Answers2

5

For SPQuery, use SPQuery.Folder to define the folder:

SPFolder folder = list.RootFolder.SubFolders["Folder 1"];

SPQuery query = new SPQuery();
query.Folder = folder;

Then, to define content type, you should include the following condition into your Where clause:

SPContentType contentType = list.ContentTypes["MyContentType"];
query.Query = "<Where><Eq><FieldRef Name='ContentTypeId' /><Value Type='Text'>" + contentType.Id + "</Value></Eq></Where>";

Then, to include all subfolders of "Folder 1", you should specify Scope="Recursive" in the query ViewAttributes:

query.ViewAttributes = "Scope=\"Recursive\"";

P.S. In case you're using Client Object Model and CamlQuery, the syntax will be a bit different. I.e. instead of Folder, you will need FolderServerRelativeUrl:

query.FolderServerRelativeUrl = "/Shared Documents/Folder 1";

And also recursive scope is defined as attribute of the View element, which in this case should be included into query.

Andrey Markeev
  • 16,286
  • 3
  • 40
  • 70
  • Great answer, but instead of "Name='ContentType'" it must be "Name='ContentTypeId'" when u use contentType.Id. Works perfectly! – Markus S Feb 08 '13 at 13:38
  • Oh, my bad, just grabbed this piece from internet and didn't test it :( I'll correct the answer for further readers, thanks! – Andrey Markeev Feb 08 '13 at 14:08
0

You can create CAML query that looks something like this (I've ommited the unrelated parts):

<View>
..........
    <QueryOptions>
        <ViewAttributes Scope='Recursive' />
    </QueryOptions>
    <Query>
      <Where>
          <And>
              <Eq>
                  <FieldRef Name="ContentType"></FieldRef>
                  <Value Type="Text">$Resources:ResourceFileName,ContentTypeName</Value>
              </Eq>
              <Eq>
                  <FieldRef Name="FileDirRef"></FieldRef>
                  <Value Type="Text">Server Relative URL of the Folder</Value>
              </Eq>
          </And>
      </Where>
    </Query>
..........
</View> 

This will return all the documents of the specified content type in the specified subfolder.

Here are some links that might be useful:
Get Items Under Folder CAML and Filter Document library folder through CAML Query