SaveFileDialog.OpenFile 方法

定义

打开用户选定的具有读/写权限的文件。

public:
 System::IO::Stream ^ OpenFile();
public System.IO.Stream OpenFile ();
member this.OpenFile : unit -> System.IO.Stream
Public Function OpenFile () As Stream

返回

Stream

用户选定的读/写文件。

示例

下面的代码示例演示如何使用该方法创建、 SaveFileDialog设置成员、调用 ShowDialog 对话框以及打开所选文件。 本示例要求窗体上放置一个按钮。

private:
   void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      Stream^ myStream;
      SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;
      saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
      saveFileDialog1->FilterIndex = 2;
      saveFileDialog1->RestoreDirectory = true;
      if ( saveFileDialog1->ShowDialog() == ::DialogResult::OK )
      {
         if ( (myStream = saveFileDialog1->OpenFile()) != nullptr )
         {
            
            // Code to write the stream goes here.
            myStream->Close();
         }
      }
   }
private void button1_Click(object sender, System.EventArgs e)
 {
     Stream myStream ;
     SaveFileDialog saveFileDialog1 = new SaveFileDialog();
 
     saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;
     saveFileDialog1.FilterIndex = 2 ;
     saveFileDialog1.RestoreDirectory = true ;
 
     if(saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         if((myStream = saveFileDialog1.OpenFile()) != null)
         {
             // Code to write the stream goes here.
             myStream.Close();
         }
     }
 }
Private Sub button1_Click(sender As Object, e As System.EventArgs)
    Dim myStream As Stream
    Dim saveFileDialog1 As New SaveFileDialog()
    
    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True
    
    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        myStream = saveFileDialog1.OpenFile()
        If (myStream IsNot Nothing) Then
            ' Code to write the stream goes here.
            myStream.Close()
        End If
    End If
End Sub

注解

注意

出于安全考虑,此方法创建一个具有所选名称的新文件,并使用读/写权限将其打开。 如果选择要保存到的现有文件,这可能会导致意外丢失数据。 若要在保留现有数据时将数据保存到现有文件,请使用 File 类使用属性中返回的 FileName 文件名打开该文件。

适用于

另请参阅