Tuesday, September 14, 2010

Code to search files with particular extension in SharePoint's Web Application

Requirement:
To search files with particular extension [here *.doc as example].

Here to achieve the above requirement I used SharePoint's Object Model.

I downloaded those searched files to a particular folder.
Beside printing the searched files result in console and I am also logging it in a Log file.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Collections;

namespace SearchFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get folder path
            string directoryPath
                = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
                , "MyFolder");

            //Create directory if it not exist
            if (!(Directory.Exists(directoryPath)))
                Directory.CreateDirectory(directoryPath);

            //SPFile myFile = null;
            byte[] binFile;
            string filename = string.Empty;
            FileStream fs = null;
            BinaryWriter bw = null;
            SPDocumentLibrary library = null;
            string fileExtension = ".doc";
            string siteURL = "http://[server-name]:[port-number]";
            StringBuilder filesLog = new StringBuilder();

            using (SPSite site = new SPSite(siteURL))
            {
                foreach (SPWeb web in site.AllWebs)
                {
                    foreach (SPList list in web.Lists)
                    {
                        if (list.BaseType == SPBaseType.DocumentLibrary)
                        {
                            library = (SPDocumentLibrary)list;
                            SPFolder folder = library.RootFolder;
                            ArrayList foldersList = new ArrayList();
                            foldersList.Add(folder);

                            foldersList = getFolders(folder, foldersList);

                            //foreach (SPListItem oListItem in library.Items)
                            foreach (SPFolder fold in foldersList)
                            {
                                foreach (SPFile myFile in fold.Files)
                                {
                                    //Download file in file system
                                    //myFile = oListItem.File;
                                    if (myFile.Name.EndsWith(fileExtension,
                                        StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        binFile = myFile.OpenBinary();

                                        //Generate file name
                                        //filename = Path.Combine(directoryPath, myFile.Name);
                                        filename 
                                           = Path.Combine(directoryPath, 
                                                          myFile.Url.Replace("/", "_"));

                                        //Do file write operation
                                        fs 
                                          = new FileStream(filename, 
                                                FileMode.Create, FileAccess.ReadWrite);
                                        bw = new BinaryWriter(fs);
                                        bw.Write(binFile);
                                        bw.Close();

                                        filesLog.Append(string.Concat(web.Url, "/", 
                                                        myFile.Url, ","));
                                        Console.WriteLine(string.Concat(web.Url, "/",
                                                        myFile.Url));

                                    }//End file extension check 
                                }//End All SPFiles
                            }//End All SPFolders
                        }//End check DocumentLibrary
                    }//End All Lists
                }//End AllWebs
            }//End SPSite

            string[] lines = filesLog.ToString().Split(new char[] { ',' });
            System.IO.File.WriteAllLines(directoryPath + "/LOG_List.txt", lines);

            Console.WriteLine("Press any key to Exit...");
            Console.ReadLine();
        }

        //Recursive function to get all nested SPFolders
        static ArrayList getFolders(SPFolder folder, ArrayList foldersList)
        {
            foreach (SPFolder subfolder in folder.SubFolders)
            {
                foldersList.Add(subfolder);
                foldersList = getFolders(subfolder, foldersList);
            }
            return foldersList;
        }
    }
}


Google