Shibli
Shibli

Reputation: 6129

Win Form: SaveFileDialog

I added the following piece of code to a save button:

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{                
    FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
    StreamWriter writer = new StreamWriter(fs);
    writer.Write(twexit.Text);       // twexit is previously created  
    writer.Close();
    fs.Close();
}

When I type the name of the file and click save, it says that file does not exist. I know it does not exist but I set FileMode.Create. So, shouldnt it create file if it does not exist?

Upvotes: 2

Views: 11155

Answers (3)

Max
Max

Reputation: 66

You can simply use this:

File.WriteAllText(saveFileDialog1.FileName, twexit.Text);

instead of lot of code with stream. It create new file or overwrite it. File is class of System.Io . If you want to say if file exist, use

File.Exist(filePath)

Bye

Upvotes: 1

Ebad Masood
Ebad Masood

Reputation: 2379

Use like this:

     SaveFileDialog dlg = new SaveFileDialog();

        dlg.Filter = "csv files (*.csv)|*.csv";
        dlg.Title = "Export in CSV format";

        //decide whether we need to check file exists
        //dlg.CheckFileExists = true;

        //this is the default behaviour
        dlg.CheckPathExists = true;

        //If InitialDirectory is not specified, the default path is My Documents
        //dlg.InitialDirectory = Application.StartupPath;

        dlg.ShowDialog();
        // If the file name is not an empty string open it for saving.
        if (dlg.FileName != "")

        //alternative if you prefer this
        //if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK
            //&& dlg.FileName.Length > 0)

        {
            StreamWriter streamWriter = new StreamWriter(dlg.FileName);
            streamWriter.Write("My CSV file\r\n");
            streamWriter.Write(DateTime.Now.ToString());
            //Note streamWriter.NewLine is same as "\r\n"
            streamWriter.Write(streamWriter.NewLine);
            streamWriter.Write("\r\n");
            streamWriter.Write("Column1, Column2\r\n");
            //…
            streamWriter.Close();
        }

        //if no longer needed
        //dlg.Dispose();

Upvotes: 0

C.Evenhuis
C.Evenhuis

Reputation: 26436

There is an option CheckFileExists in SaveFileDialog which will cause the dialog to show that message if the selected file doesn't exist. You should leave this set to false (this is the default value).

Upvotes: 4

Related Questions