OpenFileDialog.OpenFile Method ()


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public Stream OpenFile()

Return Value

Type: System.IO.Stream

A Stream that specifies the read-only file selected by the user.

Exception Condition

The file name is null.

The OpenFile method is used to provide a facility to quickly open a file from the dialog box. The file is opened in read-only mode for security purposes. To open a file in read/write mode, you must use another method, such as FileStream.

The following code example demonstrates how to use the OpenFile method.

private void button1_Click(object sender, System.EventArgs e)
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
            if ((myStream = openFileDialog1.OpenFile()) != null)
                using (myStream)
                    // Insert code to read the stream here.
        catch (Exception ex)
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);


to open a file. Associated enumeration: FileDialogPermissionAccess.Open.

.NET Framework
Available since 1.1
Return to top