Implement Save As and Save in C#

Asked

Viewed 180 times

0

You know that basic difference between salvage and the save as of the text editors? So, I’m wanting to put in my application only the option "save", however, after searching a lot on the net only figure out the way save as that involves the use of Openfiledialog, I wanted to know how to put in my save an option where it saves the change in the text without opening Openfiledialog.

That was the best you could do using Open:

 SaveFileDialog sfd = new SaveFileDialog();
        sfd.InitialDirectory = @"C:\";
        sfd.RestoreDirectory = true;
        sfd.FileName = "*.txt";
        sfd.DefaultExt = "txt";
        sfd.Filter = "txt files (*.txt) | *.txt";

        if(sfd.ShowDialog() == DialogResult.OK)
        {
            Stream fileStream = sfd.OpenFile();
            StreamWriter sw = new StreamWriter(fileStream);

            sw.Write(JanelaDeTxt.Text);

            sw.Close();
            fileStream.Close();           
        }
  • For that, you already have to know the path from where you will be saved, right? If not, where will it save? In this case, just pass the path to save as argument to StreamWriter

1 answer

3


Once when you save the file, you will need to first specify where this file is from. When it is the first time that will save the file, it is indifferent to the action of the button Save and Save as, because both will need an absolute location from which to save the file.

After the first save, the button Save can already function on its own. The Save as will have the same function, open the dialog and make the user choose where to save the file.

To the button Save, you can make a simple conditional with a variable in scope at class level where you store the last location the file was saved. If this variable is empty, then the button Save triggers the function of Save as. In the instructions of Save as, assigns the location value to this variable.

class Form1 {
   public string LastSaveLocation = "";

   public void SalvarComo() {
      SaveFileDialog sv = new SaveFileDialog() { .Filter = "Arquivos de texto|*.txt" };
      sv.ShowDialog();

      if (sv.Filename != "") {
         LastSaveLocation = sv.Filename;
         System.IO.File.WriteAllText(LastSaveLocation, JanelaDeTxt.Text);
      }
   }

   public void Salvar() {
      if (LastSaveLocation == "") {
         SalvarComo();
      } else {
         System.IO.File.WriteAllText(LastSaveLocation, JanelaDeTxt.Text);
      }
   }
}

In the code above, LastSaveLocation will have the location of the file that was saved using the SalvarComo. It will always be updated if the user determines another place to save.

Associate these methods with your Save and Save as, and also do not forget to declare the LastSaveLocation as an instance variable to the class scope.

  • 1

    Thank very Much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.