views:

71

answers:

1

i can save a file using savefiledialog . once the file is saved and if we edit it and then save it again then it should be saved without opening the savefiledialog.please help me with the code.

This code is made in Visual Studio 2005 in Windows forms.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

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

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamReader str = new StreamReader(openFileDialog1.FileName);
                textBox1.Text = str.ReadToEnd();
                str.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                {
                    StreamWriter wtr = new StreamWriter(saveFileDialog1.FileName);
                    wtr.Write(textBox1.Text);
                    wtr.Close();
                }
            }
        }

    }
}
+4  A: 

SaveFileDialog only permits you to provide a consistent user interface to the user in order for them to choose the location of the file. It does not save the actuall file for you. You have to do that yourself.

You have to provide the additional functionality you describe. You have to keep note of the file name and you have manage the logic that says: If this file is modified and I have a filename already then I save to the existing filename.

ADDITIONAL BASED ON NEW CODE

You still have to provide the logic to work out if you need to show the dialog or not. When you show the dialog for the first time you want to store the filename somewhere. Each subsequent time you want to check if you already have a file name and use that, else show the dialog.

You might also want to refactor some of that code as the code to actually save the file may be used in several places. You can put that all in one method can call that method from each place you are saving the file.

Finally, it might make reading the code a lot easier if the form and controls on the form were given proper names. button1 as the name of a control is not acceptable and if you were on my team I'd be asking you to change it so we would know what button1 actually relates to. I presume a more sensible name should be something like openFileButton and button2 should be saveFileButton.

Colin Mackay
i HAVE UPDATED THE QUESTION WITH code I am trying to use..