SharePoint 2010:Accessing All Document In a Document Library Irrespective of the folder structure
The other day I was required to write a method that would return a datatable filled with all the documents in a particular document Library irrespective of the folders insider that specific Doc Lib.
I took a slightly different approach than I usually take, since I did not have to consider the folder and instead all the files inside. So I used a CAML query as follows
Query.ViewAttributes = "Scope=\"Recursive\"";
Following is the method that takes customer ID a paramter and returns all the document against it. The method eventually turned very complex as there were a lot features such SharePoint NTLM security token, property bags and the Mime types were coded. But here is the simplest version:
public DataTable GetListofDocuments(string cusID)
{
DataTable dtFiles = new DataTable("Documents");
dtFiles.Columns.Add("Url", typeof(string));
dtFiles.Columns.Add("FileName", typeof(string));
dtFiles.Columns.Add("FileSize", typeof(int));
dtFiles.Columns.Add("Modified", typeof(DateTime));
dtFiles.Columns.Add("IsSecure", typeof(bool));
if (cusID == string.Empty)
{
throw new Exception();
}
string docPath = "MyDocLib";
using (SPSite site = new SPSite("http://vhyder"))
{
using (SPWeb oWebsite = site.OpenWeb())
{
try
{
SPList oList = oWebsite.Lists[docPath];
SPView oView = oList.Views[docLibView];
SPQuery oQuery = new SPQuery(oView);
oQuery.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection collListItemsAvailable = oList.GetItems(oQuery);
foreach (SPListItem oListItemAvailable in collListItemsAvailable)
{
if (oListItemAvailable[colCustomer] != null && oListItemAvailable[colCustomer].ToString() != string.Empty)
{
string customerID = oListItemAvailable[colCustomer].ToString();
if (customerID == cusID)
{
string[] docNameSlices = oListItemAvailable.Name.ToString().Split('.');
dtFiles.Rows.Add(oListItemAvailable.Url, oListItemAvailable.Name, oListItemAvailable.File.Length, oListItemAvailable["Modified"], oListItemAvailable["IsSecure"]);
}
}
}
}
catch (Exception)
{
throw;
}
}
}
return dtFiles;
}
Excellent post...You saved my life.:)
ReplyDelete