ARTICLE

OpenFileDialog in C#

Posted by Mahesh Chand Articles | Windows Controls C# June 11, 2010
An OpenFileDialog control is used to browse and select a file on a computer. This article demonstrates how to use a windows Forms open file dialog in C#.
Reader Level:
 

An OpenFileDialog control is used to browse and select a file on a computer. A typical Open File Dialog looks like Figure 1 where you can see Windows Explorer like features to navigate through folders and select a file.

OpenFileDlgImg1.jpg
Figure 1

Creating a OpenFileDialog

We can create an OpenFileDialog control using a Forms designer at design-time or using the OpenFileDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms controls, an OpenFileDialog does not have and not need visual properties like others. The only purpose of OpenFileDialog to display available colors, create custom colors and select a color from these colors. Once a color is selected, we need that color in our code so we can apply it on other controls.

Again, you can create an OpenFileDialog at design-time but it is easier to create an OpenFileDialog at run-time.

Design-time

To create an OpenFileDialog control at design-time, you simply drag and drop an OpenFileDialog control from Toolbox to a Form in Visual Studio. After you drag and drop an OpenFileDialog on a Form, the OpenFileDialog looks like Figure 2.

OpenFileDlgImg2.jpg
Figure 2

Adding an OpenFileDialog to a Form adds following two lines of code.

 

private System.Windows.Forms.OpenFileDialog openFileDialog1;

this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();

Run-time

Creating a OpenFileDialog control at run-time is merely a work of creating an instance of OpenFileDialog class, set its properties and add OpenFileDialog class to the Form controls.

First step to create a dynamic OpenFileDialog is to create an instance of OpenFileDialog class. The following code snippet creates an OpenFileDialog control object.

OpenFileDialog openFileDialog1 = new OpenFileDialog();

 

ShowDialog method displays the OpenFileDialog.

openFileDialog1.ShowDialog();

 

Once the ShowDialog method is called, you can browse and select a file.

 

Setting OpenFileDialog Properties

After you place an OpenFileDialog control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 3.

OpenFileDlgImg3.jpg
Figure 3

Initial and Restore Directories

InitialDirectory property represents the directory to be displayed when the open file dialog appears first time.

openFileDialog1.InitialDirectory = @"C:\";

 

If RestoreDirectory property set to true that means the open file dialogg box restores the current directory before closing.

openFileDialog1.RestoreDirectory = true;

Title

Title property is used to set or get the title of the open file dialog.

openFileDialog1.Title = "Browse Text Files";

Default Extension

DefaultExtn property represents the the default file name extension.

openFileDialog1.DefaultExt = "txt";

Filter and Filter Index

Filter property represents the filter on an open file dialog that is used to filter the type of files to be loaded during the browse option in an open file dialog. For example, if you need users to restrict to image files only, we can set Filter property to load image files only.

openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

FilterIndex property represents the index of the filter currently selected in the file dialog box.

openFileDialog1.FilterIndex = 2;

Check File Exists and Check Path Exists

CheckFileExists property indicates whether the dialog box displays a warning if the user specifies a file name that does not exist. CheckPathExists property indicates whether the dialog box displays a warning if the user specifies a path that does not exist.

openFileDialog1.CheckFileExists = true;

openFileDialog1.CheckPathExists = true;

File Name and File Names

FileName property represents the file name selected in the open file dialog.

textBox1.Text = openFileDialog1.FileName;

If MultiSelect property is set to true that means the open file dialog box allows multiple file selection. The FileNames property represents all the files selected in the selection.

this.openFileDialog1.Multiselect = true;

foreach (String file in openFileDialog1.FileNames)
{
  MessageBox.Show(file);
}

Read Only Checked and Show Read Only Files

ReadOnlyChecked property represents whether the read-only checkbox is selected and ShowReadOnly property represents whether the read-only checkbox is available or not.

openFileDialog1.ReadOnlyChecked = true;

openFileDialog1.ShowReadOnly = true;

Using OpenFileDialog in Applications

Now let's create an application that will use an OpenFileDialog that has two Button controls, a TextBox, and a container control. The Form looks like Figure 4.

OpenFileDlgImg4.jpg
Figure 4

The Browse button click event handler will show an open file dialog and users will be able to select text files. The open file dialog looks like Figure 5.

OpenFileDlgImg5.jpg
Figure 5

The following code snippet is the code for Browse button click event handler. Once a text file is selected, the name of the text file is displayed in the TextBox.

private void BrowseButton_Click(object sender, EventArgs e)

{

    OpenFileDialog openFileDialog1 = new OpenFileDialog();

 

    openFileDialog1.InitialDirectory = @"C:\";

    openFileDialog1.Title = "Browse Text Files";

 

    openFileDialog1.CheckFileExists = true;

    openFileDialog1.CheckPathExists = true;

 

    openFileDialog1.DefaultExt = "txt";

    openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

    openFileDialog1.FilterIndex = 2;

    openFileDialog1.RestoreDirectory = true;

 

    openFileDialog1.ReadOnlyChecked = true;

    openFileDialog1.ShowReadOnly = true;

 

    if (openFileDialog1.ShowDialog() == DialogResult.OK)

    {

        textBox1.Text = openFileDialog1.FileName;

    }

}

 

The code for Browse Multiple Files button click event handler looks like following.

private void BrowseMultipleButton_Click(object sender, EventArgs e)

{

        this.openFileDialog1.Filter =

        "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +

        "All files (*.*)|*.*";

 

    this.openFileDialog1.Multiselect = true;

    this.openFileDialog1.Title = "Select Photos";

 

        DialogResult dr = this.openFileDialog1.ShowDialog();

        if (dr == System.Windows.Forms.DialogResult.OK)

        {

            foreach (String file in openFileDialog1.FileNames)

            {

                try

                {

                    PictureBox imageControl = new PictureBox();

                    imageControl.Height = 100;

                    imageControl.Width = 100;

 

                    Image.GetThumbnailImageAbort myCallback =

                            new Image.GetThumbnailImageAbort(ThumbnailCallback);

                    Bitmap myBitmap = new Bitmap(file);

                    Image myThumbnail = myBitmap.GetThumbnailImage(96, 96,

                        myCallback, IntPtr.Zero);

                    imageControl.Image = myThumbnail;

 

                    PhotoGallary.Controls.Add(imageControl);

                }

                catch (Exception ex)

                {

                    MessageBox.Show("Error: " + ex.Message);

                }

            }

        }

}

 

public bool ThumbnailCallback()

{

    return false;

}

 

Summary
An OpenFileDialog control allows users to launch Windows Open File Dialog and let them select files. In this article, we discussed how to use a Windows Open File Dialog and set its properties in a Windows Forms application.

Article Extensions
Contents added by josey oommen on May 28, 2013
2:32:11 PM
Contents added by Nilesh Kelhe on Jul 10, 2012
COMMENT USING

Trending up