Timothy Goodes
Timothy Goodes

Reputation: 67

Trying to save file without using SaveFileDialog

I am creating a text editor and i am stuck on the SaveFileDialog window opening and asking to overwrite the current file open.

I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog

I got stuck on my program having a problem with FileName.

Here is the code i have currently

namespace Text_Editor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            open.Title = "Open File";
            open.FileName = "";

            if (open.ShowDialog() == DialogResult.OK)
            {
                this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
                StreamReader reader = new StreamReader(open.FileName);
                richTextBox1.Text = reader.ReadToEnd();
                reader.Close();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();

            save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            save.Title = "Save File";

            save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (save.ShowDialog() == DialogResult.OK)
            {
                StreamWriter writer = new StreamWriter(save.FileName);
                writer.Write(richTextBox1.Text);
                writer.Close();
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saving = new SaveFileDialog();

            saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            saving.Title = "Save As";
            saving.FileName = "Untitled";

            if (saving.ShowDialog() == DialogResult.OK)
            {
                StreamWriter writing = new StreamWriter(saving.FileName);
                writing.Write(richTextBox1.Text);
                writing.Close();
            }
        }

    }
}

So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?

I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.

Upvotes: 0

Views: 6869

Answers (4)

Pradeep Kumar
Pradeep Kumar

Reputation: 6969

When opening the file, save the FileName in a form-level variable or property.

Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.

First declare a variable to hold filename at form level

// declare at form level
private string FileName = string.Empty;

When opening a file, save the FileName in this variable

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();

    open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
    open.Title = "Open File";
    open.FileName = "";

    if (open.ShowDialog() == DialogResult.OK)
    {
        // save the opened FileName in our variable
        this.FileName = open.FileName;
        this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
        StreamReader reader = new StreamReader(open.FileName);
        richTextBox1.Text = reader.ReadToEnd();
        reader.Close();
    }
}

And when doing SaveAs operation, update this variable

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    SaveFileDialog saving = new SaveFileDialog();

    saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
    saving.Title = "Save As";
    saving.FileName = "Untitled";

    if (saving.ShowDialog() == DialogResult.OK)
    {
        // save the new FileName in our variable
        this.FileName = saving.FileName;
        StreamWriter writing = new StreamWriter(saving.FileName);
        writing.Write(richTextBox1.Text);
        writing.Close();
    }
}

The save function can then be modified like this:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(this.FileName))
    {
        // call SaveAs 
        saveAsToolStripMenuItem_Click(sender, e);
    } else {
        // we already have the filename. we overwrite that file.
        StreamWriter writer = new StreamWriter(this.FileName);
        writer.Write(richTextBox1.Text);
        writer.Close();
    }
}

In the New (and Close) function, you should clear this variable

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
    // clear the FileName
    this.FileName = string.Empty;
    richTextBox1.Clear();
}

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement

  public partial class Form1: Form {
    // File name to save text to  
    private String m_FileName = "";

    private Boolean SaveText(Boolean showDialog) {
      // If file name is not assigned or dialog explictly required
      if (String.IsNullOrEmpty(m_FileName) || showDialog) {
        // Wrap IDisposable into using
        using (SaveFileDialog dlg = new SaveFileDialog()) {
          dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
          dlg.Title = "Save File";
          dlg.FileName = m_FileName;  

          if (dlg.ShowDialog() != DialogResult.OK) 
            return false;

          m_FileName = dlg.FileName;  
        } 
      }

      File.WriteAllText(m_FileName, richTextBox1.Text);

      this.Text = Path.GetFileNameWithoutExtension(m_FileName);

      return true;
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
      // SaveAs: always show the dialog 
      SaveText(true);
    }

    private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
      // Save: show the dialog when required only
      SaveText(false);
    }
    ...
  }

Upvotes: 1

Sebi
Sebi

Reputation: 71

Create a new string variable in your class for example string filename = string.empty

and then

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
  if(string.IsNullOrEmpty(filename)) {
 //Show Save filedialog
    SaveFileDialog save = new SaveFileDialog();

    save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
    save.Title = "Save File";

    save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    if (save.ShowDialog() == DialogResult.OK)
    {
        filename = save.FileName;

    }
   }
   StreamWriter writer = new StreamWriter(filename);
        writer.Write(richTextBox1.Text);
        writer.Close();
}

The SaveFileDialog now only opens if fileName is null or empty

Upvotes: 4

donmartin
donmartin

Reputation: 1973

You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).

Give it a try, do the following:

  • Define a string member variable, call it _fileName (private string _fileName; in your class)
  • In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
  • If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
  • Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName

Have fun, C# is a great language to program in.

Upvotes: 2

Related Questions