Como salvar arquivos usando o componente SaveFileDialog

O SaveFileDialog componente permite que os usuários naveguem pelo sistema de arquivos e selecionem os arquivos a serem salvos. A caixa de diálogo retorna o caminho e o nome do arquivo que o usuário selecionou na caixa de diálogo. No entanto, você deve escrever o código para efetivamente gravar os arquivos no disco.

Salvar arquivos usando o componente SaveFileDialog

  • Exiba a caixa de diálogo Salvar Arquivo e chame um método para salvar o arquivo selecionado pelo usuário.

    Use o método do OpenFile componente para salvar o SaveFileDialog arquivo. Esse método fornece um Stream objeto no qual você pode gravar.

    O exemplo abaixo usa a DialogResult propriedade para obter o nome do arquivo e o método para salvar o OpenFile arquivo. O OpenFile método fornece um fluxo para gravar o arquivo.

    No exemplo abaixo, há um Button controle com uma imagem atribuída a ele. Quando você clica no botão, um componente é instanciado com um SaveFileDialog filtro que permite arquivos do tipo .gif, .jpeg e .bmp. Se um arquivo desse tipo for selecionado na caixa de diálogo Salvar Arquivo, a imagem do botão será salva.

    Importante

    Para obter ou definir a FileName propriedade, seu assembly requer um nível de privilégio concedido pela System.Security.Permissions.FileIOPermission classe. Se você estiver executando em um contexto de confiança parcial, o processo poderá gerar uma exceção em razão dos privilégios insuficientes. Para obter mais informações, consulte Noções Básicas da Segurança de Acesso do Código.

    O exemplo pressupõe que seu formulário tenha um controle com sua Image propriedade definida como um Button arquivo do tipo .gif, .jpeg ou .bmp.

    Observação

    A FileDialog propriedade da classe (que, devido à herança, faz parte da FilterIndexSaveFileDialog classe) usa um índice baseado em um. Isso será importante se você estiver escrevendo código para salvar dados em um formato específico (por exemplo, salvar um arquivo como texto sem formatação em vez de formato binário). Essa propriedade é apresentada no exemplo abaixo.

    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# e Visual C++) Coloque o código a seguir no construtor do formulário para registrar o manipulador de eventos.

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

    Para obter mais informações sobre como gravar fluxos de arquivos, consulte BeginWrite e Write.

    Observação

    Certos controles, como o RichTextBox controle, têm a capacidade de salvar arquivos.

Confira também