Free language processing service and NLP C# code
Select Multiple Files From More Than One Directory

NLP Task

Visual C# makes selecting files very easy. This sample code illustrates how to select as many files as you like from more than one directory.

Algorithms and Implementation

Create a HashSet<string> to hold the files selected so far. As we know from previous sample code pages, HashSet automatically removes duplicated items which is ideal for our purpose, as we do not want the same file path to appear more than once.

Create a DialogResult which will be used to detect whether user decides not to select any more files.

Create an OpenFileDialog. While setting its Multiselect property to true is required setting its RestoreDirectory to true is optional.

Unless user answers No to the question "More Files?", the OpenFileDialog keeps popping up for accepting more files. User can change his mind by clicking the Cancel button.

Code (Download)

 // This is needed 
using System.Windows.Forms;

public class YourClass

   /// <summary>
   ///  It captures the file names opened from a single or multiple folders.
   ///  User is given the chance to stop adding files by clicking Cancel.
   /// </summary>
   /// <returns> a set of file paths selected by user</returns>
   public static HashSet<string> RepetitiveOpenFiles( )
       HashSet<string> filesOpened = new HashSet<string>( );
       DialogResult dr = new DialogResult( );
       OpenFileDialog ofd = new OpenFileDialog( );
       ofd.RestoreDirectory = true;
       ofd.Multiselect = true;
           if ( ofd.ShowDialog( ) == DialogResult.OK )
               string[] files = ofd.FileNames;
               foreach ( var file in files )
                   filesOpened.Add( file );
                //capture the confirmation box result 
               dr = MessageBox.Show( "More Files?" , "Add Files" , MessageBoxButtons.YesNo );
               dr = DialogResult.No;
        } while ( dr == DialogResult.Yes );
        return filesOpened;



To use this method, reference to System.Windows.Forms needs to be added.

Skip Navigation LinksHome > Nlp Sample Code > IO Skills > Select Multiple Files From More Than One Directory