Compartir a través de


Cómo: Guardar archivos mediante el componente SaveFileDialog

El SaveFileDialog componente permite a los usuarios examinar el sistema de archivos y seleccionar los archivos que se van a guardar. El cuadro de diálogo devuelve la ruta de acceso y el nombre del archivo que el usuario ha seleccionado en el cuadro de diálogo. Sin embargo, debe escribir el código para escribir realmente los archivos en el disco.

Para guardar un archivo mediante el componente SaveFileDialog

  • Muestra el cuadro de diálogo Guardar archivo y llama a un método para guardar el archivo seleccionado por el usuario.

    Use el SaveFileDialog método del OpenFile componente para guardar el archivo. Este método proporciona un Stream objeto en el que puede escribir.

    En el ejemplo siguiente se usa la DialogResult propiedad para obtener el nombre del archivo y el OpenFile método para guardar el archivo. El OpenFile método proporciona una secuencia en la que escribir el archivo.

    En el ejemplo siguiente, hay un Button control con una imagen asignada. Al hacer clic en el botón, se crea una instancia de un SaveFileDialog componente con un filtro que permite archivos de tipo .gif, .jpeg y .bmp. Si se selecciona un archivo de este tipo en el cuadro de diálogo Guardar archivo, se guarda la imagen del botón.

    Importante

    Para obtener o establecer la propiedad, el FileName ensamblado requiere un nivel de privilegio concedido por la System.Security.Permissions.FileIOPermission clase . Si se ejecuta en un contexto de confianza parcial, el proceso podría producir una excepción debido a privilegios insuficientes. Para obtener más información, consulte Conceptos básicos de seguridad de acceso al código.

    En el ejemplo se supone que el formulario tiene un Button control con su Image propiedad establecida en un archivo de tipo .gif, .jpeg o .bmp.

    Nota:

    La FileDialog propiedad de FilterIndex la clase (que, debido a la herencia, forma parte de la SaveFileDialog clase) usa un índice basado en uno. Esto es importante si está escribiendo código para guardar datos en un formato específico (por ejemplo, guardar un archivo en texto sin formato frente a formato binario). Esta propiedad se incluye en el ejemplo siguiente.

    Private Sub Button2_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button2.Click
        ' Displays a SaveFileDialog so the user can save the Image
        ' assigned to Button2.
        Dim saveFileDialog1 As New SaveFileDialog()
        saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"
        saveFileDialog1.Title = "Save an Image File"
        saveFileDialog1.ShowDialog()
    
        ' If the file name is not an empty string open it for saving.
        If saveFileDialog1.FileName <> "" Then
          ' Saves the Image via a FileStream created by the OpenFile method.
          Dim fs As System.IO.FileStream = Ctype _
              (saveFileDialog1.OpenFile(), System.IO.FileStream)
          ' Saves the Image in the appropriate ImageFormat based upon the
          ' file type selected in the dialog box.
          ' NOTE that the FilterIndex property is one-based.
          Select Case saveFileDialog1.FilterIndex
              Case 1
                Me.button2.Image.Save(fs, _
                    System.Drawing.Imaging.ImageFormat.Jpeg)
    
              Case 2
                Me.button2.Image.Save(fs, _
                    System.Drawing.Imaging.ImageFormat.Bmp)
    
              Case 3
                Me.button2.Image.Save(fs, _
                    System.Drawing.Imaging.ImageFormat.Gif)
            End Select
    
            fs.Close()
        End If
    End Sub
    
    private void button2_Click(object sender, System.EventArgs e)
    {
        // Displays a SaveFileDialog so the user can save the Image
        // assigned to Button2.
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
        saveFileDialog1.Title = "Save an Image File";
        saveFileDialog1.ShowDialog();
    
        // If the file name is not an empty string open it for saving.
        if(saveFileDialog1.FileName != "")
        {
          // Saves the Image via a FileStream created by the OpenFile method.
          System.IO.FileStream fs =
              (System.IO.FileStream)saveFileDialog1.OpenFile();
          // Saves the Image in the appropriate ImageFormat based upon the
          // File type selected in the dialog box.
          // NOTE that the FilterIndex property is one-based.
          switch(saveFileDialog1.FilterIndex)
          {
              case 1 :
              this.button2.Image.Save(fs,
                System.Drawing.Imaging.ImageFormat.Jpeg);
              break;
    
              case 2 :
              this.button2.Image.Save(fs,
                System.Drawing.Imaging.ImageFormat.Bmp);
              break;
    
              case 3 :
              this.button2.Image.Save(fs,
                System.Drawing.Imaging.ImageFormat.Gif);
              break;
          }
    
        fs.Close();
        }
    }
    
    private:
        System::Void button2_Click(System::Object ^ sender,
          System::EventArgs ^ e)
        {
          // Displays a SaveFileDialog so the user can save the Image
          // assigned to Button2.
          SaveFileDialog ^ saveFileDialog1 = new SaveFileDialog();
          saveFileDialog1->Filter =
              "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
          saveFileDialog1->Title = "Save an Image File";
          saveFileDialog1->ShowDialog();
          // If the file name is not an empty string, open it for saving.
          if(saveFileDialog1->FileName != "")
          {
              // Saves the Image through a FileStream created by
              // the OpenFile method.
              System::IO::FileStream ^ fs =
                safe_cast\<System::IO::FileStream*>(
                saveFileDialog1->OpenFile());
              // Saves the Image in the appropriate ImageFormat based on
              // the file type selected in the dialog box.
              // Note that the FilterIndex property is one based.
              switch(saveFileDialog1->FilterIndex)
              {
                case 1 :
                    this->button2->Image->Save(fs,
                      System::Drawing::Imaging::ImageFormat::Jpeg);
                    break;
                case 2 :
                    this->button2->Image->Save(fs,
                      System::Drawing::Imaging::ImageFormat::Bmp);
                    break;
                case 3 :
                    this->button2->Image->Save(fs,
                      System::Drawing::Imaging::ImageFormat::Gif);
                    break;
              }
          fs->Close();
          }
        }
    

    (Visual C# y Visual C++) Coloque el código siguiente en el constructor del formulario para registrar el controlador de eventos.

    this.button2.Click += new System.EventHandler(this.button2_Click);
    
    this->button2->Click += gcnew
        System::EventHandler(this, &Form1::button2_Click);
    

    Para obtener más información sobre cómo escribir secuencias de archivos, vea BeginWrite y Write.

    Nota:

    Algunos controles, como el RichTextBox control , tienen la capacidad de guardar archivos.

Consulte también