Share via


SaveFileDialog.OpenFile Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Opens the file specified by the SafeFileName property.

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

Syntax

'Declaration
<SecuritySafeCriticalAttribute> _
Public Function OpenFile As Stream
[SecuritySafeCriticalAttribute]
public Stream OpenFile()

Return Value

Type: System.IO.Stream
A read-write stream for the file specified by the SafeFileName property.

Exceptions

Exception Condition
InvalidOperationException

No file was selected in the dialog box.

Remarks

You should always check that the ShowDialog method returns true before accessing the stream associated with the file. Failure to do this will create an exception.

Examples

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

Private textDialog As SaveFileDialog
Public Sub New()
    InitializeComponent()
    textDialog = New SaveFileDialog()
    textDialog.Filter = "Text Files | *.txt"
    textDialog.DefaultExt = "txt"
End Sub

Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim result As System.Nullable(Of Boolean) = textDialog.ShowDialog()
    If result = True Then
        Dim fileStream As System.IO.Stream = textDialog.OpenFile()
        Dim sw As New System.IO.StreamWriter(fileStream)
        sw.WriteLine("Writing some text in the file.")
        sw.Flush()
        sw.Close()
    End If
End Sub
SaveFileDialog textDialog;
public Page()
{
    InitializeComponent();
    textDialog = new SaveFileDialog();
    textDialog.Filter = "Text Files | *.txt";
    textDialog.DefaultExt = "txt";
 }

private void button1_Click(object sender, RoutedEventArgs e)
{
    bool? result = textDialog.ShowDialog();
    if (result == true)
    {
        System.IO.Stream fileStream = textDialog.OpenFile();
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream);
        sw.WriteLine("Writing some text in the file.");
        sw.Flush();
        sw.Close();
    }
}
<Grid x:Name="LayoutRoot" Background="White">
     <Button Height="100" Width="100" Content="Save Text File" x:Name="button1" 
        Click="button1_Click"  />
</Grid>

Version Information

Silverlight

Supported in: 5, 4, 3

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.