SaveFileDialog.OpenFile Method (System.Windows.Controls)

Switch View :
ScriptFree
.NET Framework Class Library for Silverlight
SaveFileDialog.OpenFile Method

Opens the file specified by the SafeFileName property.

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

Visual Basic (Declaration)
<SecuritySafeCriticalAttribute> _
Public Function OpenFile As Stream
C#
[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.

Visual Basic

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


C#

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();
    }
}


XAML

<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.

See Also

Reference