SharePoint - how to find all files from a document library and also from folder

Asked By Alok on 28-Jul-11 09:40 AM
Hi All

how to find all files from a document library and also from folder under the same document library in C#.

thanks in advance


Jitendra Faye replied to Alok on 28-Jul-11 09:45 AM
Open your document library and create a new view with the name CurrentUserDocuments.

Expand the filter category, Select the Show items only when the following option and select the Created By column in the first drop down. Select the is equal to option in the second drop down. Enter [Me] in the third text box and save the view.
Now set this view as default one, and test this with different user logins. You can also add this library as a web part in any page and set CurrentUserDocuments view as a default one.

If you are using the custom web part, create the mentioned view above and use the following code:

public void GetDocumentsForCurrentUser()
{
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["Library Name"];
SPQuery query = new SPQuery(list.Views["CurrentUserDocuments"]);
list.GetItems(query);
foreach (SPListItem item in list.Items)
{
//write your code here to display the details in web part
//If you are refer some custom fields here, you must need to
//select that fields in CurrentUserDocuments view
}
}

Hope this will help you.
Reena Jain replied to Alok on 28-Jul-11 09:45 AM
Hi,

Try the following code and let me know the results.

using System;
using System.IO;
using System.Xml;
using System.IO.Packaging;
using Microsoft.SharePoint;
namespace Jatin
{
  public class Program
  {
  public static void Main(string[] args)
  {
    using (SPSite site = new SPSite("http://localhost:20918"))
    {
    using (SPWeb web = site.OpenWeb())
    {
      string fileName = "myFile.docx";
      string documentLibName = "My documents";
      string fileUrl = string.Format("{0}/{1}/{2}", web.Url, documentLibName, fileName);
      SPFile file = web.GetFile(fileUrl);
      if (file.Exists)
      Console.WriteLine("File {0} exists in the site!!!", file.Name);
      else
      Console.WriteLine("File not found!!!");
    }
    }
  }
  }
}

Hope this will help you
Alok replied to Reena Jain on 28-Jul-11 09:50 AM
Hi

thankx for reply

but i want all the files from document library.
Ravi S replied to Alok on 28-Jul-11 09:53 AM
HI

Get files from directory

Method Directory.GetFiles returns string array with files names (full paths).

[C#]
using System.IO;
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
// returns:
// "c:\MyDir\my-car.BMP"
// "c:\MyDir\my-house.jpg"

Get files from directory (with specified extension)

You can specify search pattern. You can use wildcard specifiers in the search pattern, e.g. „*.bmp“ to select files with the extension or „a*“ to select files beginning with letter „a“.

[C#]
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");
// returns:
// "c:\MyDir\my-car.BMP"

Get files from directory (including all subdirectories)

If you want to search also in subfolders use parameter SearchOption.A­llDirectories.

[C#]
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp",
                                         SearchOption.AllDirectories);
// returns:
// "c:\MyDir\my-car.BMP"
// "c:\MyDir\Friends\james.BMP"
Alok replied to Jitendra Faye on 28-Jul-11 09:55 AM
thanks for reply

this code give the erron on line

SPQuery query = new SPQuery(list.Views["CurrentUserDocuments"]);
view is not exist.
Radhika roy replied to Alok on 28-Jul-11 10:47 AM

Use this code-

public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

ClientContext clientCtx;
Microsoft.SharePoint.Client.List docs;
int FileCounter= 0;

private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{

clientCtx = new ClientContext(ApplicationContext.Current.Url);
clientCtx.Load(clientCtx.Web);
clientCtx.Load(clientCtx.Web.Lists);
docs = clientCtx.Web.Lists.GetByTitle(“My Documents”);
clientCtx.Load(docs);
clientCtx.Load(docs.Rootfolder);
clientCtx.Load(docs.Rootfolder.Files);
clientCtx.ExecuteQueryAsync(loadSiteData, null); // We will move to loadSiteData method on success
}

void loadSiteData(Object sender, ClientRequestSucceededEventArgs e)
{
//This method starts on a background thread, but we need to work on UI to display our files Therefore we call Dispatcher.BeginInvoke() to perform the UI updating on the main thread
Dispatcher.BeginInvoke(addFiles);
}

void addFiles()
{
foreach (File doc in docs.Rootfolder.Files)
{
clientCtx.Load(doc);
clientCtx.ExecuteQueryAsync(addFiletoUI, null); // We will move to loadSiteData method on success
}
}

void addFiletoUI(Object sender, ClientRequestSucceededEventArgs e)
{
Dispatcher.BeginInvoke(addFile);
}

void addFile()
{
string filename = docs.Rootfolder.Files[FileCounter].Name;
string fileUrl = docs.Rootfolder.Files[FileCounter].ServerRelativeUrl;
HyperlinkButton fLink= new HyperlinkButton();
fLink.Content = filename;
fLink.NavigateUri = new Uri(fileUrl , UriKind.Relative);
mypanel.Children.Add(fLink);
FileCounter++;
}
}


Hope this will help you.


Hope this will help you.

Reena Jain replied to Alok on 28-Jul-11 01:09 PM
Hi,

Use this code to get all the document library-
 
using(SPSite site = new SPSite("http://myserverurl"))
{
   using(SPWeb rootWeb = site.OpenWeb())
   {
   ActionDocLibRecursive(rootWeb);
   }
}
 
 
The recursive method would be as follows:
 
private void ActionDocLibRecursive(SPWeb web)
{
  // loop through each list in the web site
  foreach(SPList list in web.Lists)
  {
  // check if the list is a document library
    if(list.BaseType == SPBaseType.DocumentLibrary)
    {
    // if it is, create a document library object
    SPDocumentLibrary docLib = (SPDocumentLibrary)list;
    // check that the document library is not a "catalog"
    // (e.g. "Master Pages & Page Layouts" .. or "Web Template Gallery")
    if(docLib.IsCatalog == false)
    {
        // perform action .. you've found a document library
        // and it's not a "Catalog" !
    }
  }
}
 
// call the recursive loop back on itself
 
  foreach(SPWeb subWeb in web.Webs)
  {
    // call resursive method on each sub-site of the current site
    ActionDocLibRecursive(subWeb);
  }
}

Hope this will help you