This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

The Open File Dialog Box

The OpenFileDialog class provides one of the .NET framework's common dialog boxes. This standardised dialog box allows users to select a single file or a group of files to be opened.

The OpenFile Method

In many situations it's a good idea to read the FileName or FileNames property and manually perform any actions. In some cases though, you might simply want to open a selected file as a read-only stream. The dialog box includes some built-in functionality for this purpose in the OpenFile method. This method returns a Stream object that you can use to read information from the file. It is most useful when Multiselect is disabled. If Multiselect is set to true, only one file is opened. This is the one specified in the FileName property, and is usually the last one that the user selected.

Update the click method code for the button as follows to add an extra call after the user clicks OK:

private void OpenButton_Click(object sender, EventArgs e)
    using (OpenFileDialog ofd = new OpenFileDialog())
        ofd.Multiselect = true;
        ofd.Filter = "Text Files|*.txt|Images|*.gif;*.jpg;*.png";
        ofd.FilterIndex = 2;
        ofd.Title = "Pick some files to process";
        ofd.InitialDirectory = @"c:\windows";
        ofd.CheckFileExists = false;
        ofd.CheckPathExists = false;
        ofd.ShowReadOnly = true;
        ofd.ReadOnlyChecked = true;

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

Next, add a method that opens the file with the OpenFile method and displays the file length:

private void ShowFileLength(OpenFileDialog ofd)
    using (Stream a = ofd.OpenFile())
        MessageBox.Show(a.Length.ToString() + " bytes");

Try running the program and selecting a file to see the results.

23 March 2014