SharePoint: Create a view to show all items without folders

Scenario: Create a view in document library  to show all items without folders using object model.



Solution: I first tried this solution but it did not work.
using (SPSite site = new SPSite("http://intranet.contoso.com/sites/contracts"))
{
    using (SPWeb web = site.OpenWeb())
    {
        char[] ViewFieldSepartors = new char[] { ';' };
        string viewFields = "Title;Department";
        SPList list = web.Lists["DOC1"];
        SPQuery query = new SPQuery();
        query.Query = "<QueryOptions><ViewAttributes Scope='Recursive' /></QueryOptions>";
        StringCollection fields = new StringCollection();
        fields.AddRange(viewFields.Split(ViewFieldSepartors, System.StringSplitOptions.RemoveEmptyEntries));
        SPView view = list.Views.Add("TestView", fields, query.Query, 100, true, false);
        list.Update();
    }
}

Then I created the required view using UI and checked the generated CAML using SPManager and found that SPView.Scope property needs to be set to Recursive in order to show all items without folders. Following is the code for that:

using (SPSite site = new SPSite("http://intranet.contoso.com/sites/contracts"))
{
    using (SPWeb web = site.OpenWeb())
    {
        char[] ViewFieldSepartors = new char[] { ';' };
        string viewFields = "Title;Department";
        SPList list = web.Lists["DOC1"];
        StringCollection fields = new StringCollection();
        fields.AddRange(viewFields.Split(ViewFieldSepartors, System.StringSplitOptions.RemoveEmptyEntries));
        SPView view = list.Views.Add("TestView", fields, string.Empty, 100, true, false);
        view.Scope = SPViewScope.Recursive;
        view.Update();
        list.Update();
    }
}
profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+