Select Multiple Files using OpenFileDialog in C#

This code snippet contains a custom function for selecting multiple files using OpenFileDialog in C#.

Where you can use OpenFileDialog:

To select multiple files programmatically instead of using any component. Using any readymade component consumes more memory than accessing same functionality using direct code snippet.

About OpenFileDialog:
According to Microsoft’s MSDN – “OpenFileDialog displays a standard dialog box that prompts the user to open a file. This class cannot be inherited.”

In simple words, OpenFileDialog allows you to browse folder(s) and select the file(s).

Namespace & Assembly used by OpenFileDialog:
Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

The Code:
public string[] ListFiles(){
    using (OpenFileDialog file = new OpenFileDialog())
    {
            //Allow to select multiple files
            file.Multiselect = true;

            //Allow to select only *.txt Files
            file.Filter = “Only Text Documents|*.txt”;

           //Show the Dialog box to selcet file(s)
            file.ShowDialog();

            //return input file names
            return file.FileNames;
    }
}

Summary:
As function ListFiles() has return type string[], it returns list of file names in string array for selected files using OpenFileDialog.

Regards,
Mayur Dighe
http://ImmortalDotNet.blogspot.com
http://MayurDighe.wordpress.com