none
C# search directory path

    Question

  • I am working on setting up a C# 2010 application that will search directory file paths to see when there has been a files added to the directory since the last time the directory was searched. I basically want to look for the following:
    1. files that end with *.xls or *.xlsx.
    2. I will look for files in the 'highest' level directory path and serach for new files that have been added since  the last time the search was made.

    Thus I am hoping  you can tell me how to accomplish this goal and/or point me to referneces that will let me how to accomplish this goal.

    Friday, October 05, 2012 9:14 PM

Answers

  • How do I check for when the file was added to the directory path

    You can use FileInfo`s properties, one of them is "LastWriteTime":

                foreach (FileInfo file in listOfFiles)
                {
                    DateTime date = file.LastWriteTime;
                }

    and to put the files that anew newer then your comparabe time, compare it with your time with "When last seach was made" you can do:

     DateTime lastSearch = new DateTime(2012, 10,6,8,10,0); //set your last searchin time
    
    //inside... 
    foreach (DirectoryInfo folder in folders)
    {
        IEnumerable<FileInfo> files = GetFilesByExtensions(new DirectoryInfo(folder.FullName), new string[] { "*.xls", "*.xlsx" });
        foreach (var file in files)
        {
            if (file.LastWriteTime > lastSearch)
                listOfFiles.Add(file);
        }
    }
    This is the same foreach loop from my upper code, I only added  another forech loop inside and a datetime checking. File will be added into the list, if "lastWriteTime" is newer then the lastSearched time.


    Mitja

    • Marked as answer by midnight_car Saturday, October 06, 2012 8:50 PM
    Saturday, October 06, 2012 7:53 PM

All replies

  • Directory.EnumerateFiles should provide all of the functionality you need: http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles.aspx

    It lets you search through the path.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Friday, October 05, 2012 9:16 PM
    Moderator
  • 2. I will look for files in the 'highest' level directory path...

    What do you mean by that? Do you mean in finaly directory in the directories structure.

    So if this example: 

    1. "C:\Folder1\Folder2.1\Folder3.1\"

    2. "C:\Folder1\Folder2.2\

    you want to do searching only inside Folder3.1 and 2.2? Becasuse these 2 folders are in the "higest" level.


    Mitja

    Friday, October 05, 2012 9:39 PM

  • 1. "C:\Folder1\Folder2.1\Folder3.1\"

    2. "C:\Folder1\Folder2.2\

    you want to do searching only inside Folder3.1 and 2.2? Becasuse these 2 folders are in the "higest" level.


    Hi Mitja,

    in my understanding these are the lowest levels - the highest is the root for me.

    see graph theory

    http://en.wikipedia.org/wiki/Depth-first_search

    http://en.wikipedia.org/wiki/Breadth-first_search

    Regards,

      Thorsten

    Saturday, October 06, 2012 3:54 PM
  • oh :)

    sorry, my bad! This this is even easier.

    This is a simple code:

            public Form1()
            {
                InitializeComponent();
                string basePath = "C:\\";
                List<FileInfo> files = LoopFoldersToGetFiles(basePath);
            }
    
            private List<FileInfo> LoopFoldersToGetFiles(string basePath)
            {
                List<FileInfo> listOfFiles = new List<FileInfo>();
                try
                {                
                    DirectoryInfo[] folders = new DirectoryInfo(basePath).GetDirectories();
                    foreach (DirectoryInfo folder in folders)
                    {
                        IEnumerable<FileInfo> files = GetFilesByExtensions(new DirectoryInfo(folder.FullName), new string[] { "*.xls", "*.xlsx" });
                        listOfFiles.AddRange(files);
                    }
                }
                catch (Exception ex)
                {
                    //throw new UnauthorizedAccessException(ex.Message);
                }
                return listOfFiles;
            }
    
            private IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, string[] extensions)
            {
                if (extensions == null)
                    throw new ArgumentNullException("Missing Extensions");
                IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>();
                foreach (string ext in extensions)
                    files = files.Concat(dir.GetFiles(ext));
                return files;
            }

    ---

    ---

    If you want to loop drives (c:\, d:\,..) then do some additional code:

            public Form1()
            {
                InitializeComponent();          
                List<FileInfo> files = LoopFoldersToGetFiles();;
            }        
    
            private List<FileInfo> LoopFoldersToGetFiles()
            {
                List<FileInfo> listOfFiles = new List<FileInfo>();
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo drive in drives)
                {
                    if (drive.Name != "A:\\" && drive.Name!= "B:\\")
                    {                   
                        try
                        {
                            DirectoryInfo[] folders = new DirectoryInfo(drive.Name).GetDirectories();
                            foreach (DirectoryInfo folder in folders)
                            {
                                IEnumerable<FileInfo> files = GetFilesByExtensions(new DirectoryInfo(folder.FullName), new string[] { "*.xls", "*.xlsx" });
                                listOfFiles.AddRange(files);
                            }
                        }
                        catch (Exception ex)
                        {
                            //throw new UnauthorizedAccessException(ex.Message);
                        }
                    }
                }
                return listOfFiles;
            }

    And use the 2nd method, which get the files.

    Hope it helps,bye


    Mitja

    • Edited by Mitja Bonca Saturday, October 06, 2012 4:17 PM
    Saturday, October 06, 2012 4:09 PM
  • Hi,

    fast, low footprint,

    see http://stackoverflow.com/questions/8548012/unauthorizedaccessexception-while-getting-files

    (modify it a little to get FileSystemInfos instead of strings for convenience)

    Regards,

      Thorsten


    Saturday, October 06, 2012 5:04 PM
  • I think this solution will just not do, becuase OP explicitly stated he wants to get files of 2 different extensions (excel files of *xls, and *xlsx).

    So there will be needed something else, and OP must not use search option like "SearchAllDirectories" - as he stated only folders on the highest level.


    Mitja

    Saturday, October 06, 2012 5:12 PM
  • Oh thanks, I havent read the OP carefully enough, but you could simply modify that to get it to work...

    Regards,

      Thorsten

    Saturday, October 06, 2012 5:16 PM
  • here's a simple version of what I meant...

    Note: credits go to http://stackoverflow.com/questions/8548012/unauthorizedaccessexception-while-getting-files, I just modified that code.

        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                //set last parameter to false to search the wtop dir only
                IEnumerable<FileSystemInfo> filesOrDirectories = FileDirectorySearcher.Search(new DirectoryInfo(@"C:\Program Files\"), "*.exe", true);
    
                filesOrDirectories = filesOrDirectories.Concat(FileDirectorySearcher.Search(new DirectoryInfo(@"C:\Program Files\"), "*.dll", true));
    
                foreach (FileSystemInfo fileOrDirectory in filesOrDirectories)
                {
                    Console.WriteLine(fileOrDirectory.FullName);
                }
            }
        }
    
        public static class FileDirectorySearcher
        {
            public static IEnumerable<FileSystemInfo> Search(DirectoryInfo searchPath, string searchPattern, bool searchWholeTree)
            {
                IEnumerable<FileSystemInfo> files = GetFileSystemEntries(searchPath, searchPattern);
    
                foreach (FileSystemInfo fi in files)
                {
                    yield return fi;
                }
    
                if (searchWholeTree)
                {
                    IEnumerable<DirectoryInfo> directories = GetDirectories(searchPath);
    
                    foreach (DirectoryInfo dir in directories)
                    {
                        files = Search(dir, searchPattern, searchWholeTree);
    
                        foreach (FileInfo fi in files)
                        {
                            yield return fi;
                        }
                    }
                }
            }
    
            private static IEnumerable<DirectoryInfo> GetDirectories(DirectoryInfo directory)
            {
                IEnumerable<DirectoryInfo> subDirectories = null;
                try
                {
                    subDirectories = directory.EnumerateDirectories("*.*", SearchOption.TopDirectoryOnly);
                }
                catch (UnauthorizedAccessException)
                {
                }
    
                if (subDirectories != null)
                {
                    foreach (DirectoryInfo subDirectory in subDirectories)
                    {
                        yield return subDirectory;
                    }
                }
            }
    
            private static IEnumerable<FileSystemInfo> GetFileSystemEntries(DirectoryInfo directory, string searchPattern)
            {
                IEnumerable<FileSystemInfo> files = null;
                try
                {
                    files = directory.EnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
                }
                catch (UnauthorizedAccessException)
                {
                }
    
                if (files != null)
                {
                    foreach (FileSystemInfo fs in files)
                    {
                        yield return fs;
                    }
                }
            }
        }


    Regards,

      Thorsten

    Saturday, October 06, 2012 5:21 PM
  • How do I check for when the file was added to the directory path
    Saturday, October 06, 2012 7:28 PM
  • I want to seach at the "C:\Folder1\Folder2.2\ level?
    Saturday, October 06, 2012 7:29 PM
  • How do you ask for the date each file was added to the directory path?
    Saturday, October 06, 2012 7:31 PM
  • How do you tell when the date each file was added to the specified directory path?
    Saturday, October 06, 2012 7:36 PM
  • How do I check for when the file was added to the directory path

    You can use FileInfo`s properties, one of them is "LastWriteTime":

                foreach (FileInfo file in listOfFiles)
                {
                    DateTime date = file.LastWriteTime;
                }

    and to put the files that anew newer then your comparabe time, compare it with your time with "When last seach was made" you can do:

     DateTime lastSearch = new DateTime(2012, 10,6,8,10,0); //set your last searchin time
    
    //inside... 
    foreach (DirectoryInfo folder in folders)
    {
        IEnumerable<FileInfo> files = GetFilesByExtensions(new DirectoryInfo(folder.FullName), new string[] { "*.xls", "*.xlsx" });
        foreach (var file in files)
        {
            if (file.LastWriteTime > lastSearch)
                listOfFiles.Add(file);
        }
    }
    This is the same foreach loop from my upper code, I only added  another forech loop inside and a datetime checking. File will be added into the list, if "lastWriteTime" is newer then the lastSearched time.


    Mitja

    • Marked as answer by midnight_car Saturday, October 06, 2012 8:50 PM
    Saturday, October 06, 2012 7:53 PM