Focus
Focus

Reputation: 13

Saving Files with SaveFileDialog

I am trying to save Files with SaveFileDialog but they are not appearing on the Directory i have given.
This is what i have tried:

private void button1_Click(object sender, EventArgs e)
{
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Application.StartupPath + "\\Scripts\\";      
    saveFileDialog1.Title = "Save text Files";
    saveFileDialog1.CheckFileExists = true;
    saveFileDialog1.CheckPathExists = true;
    saveFileDialog1.DefaultExt = "txt";
    saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
    saveFileDialog1.FilterIndex = 2;
    saveFileDialog1.FileName = textBox1.Text;
    saveFileDialog1.RestoreDirectory = true;
    Executor executor = new Executor();
    this.Hide();
}

What could be the Problem?

Upvotes: 0

Views: 1365

Answers (1)

Abhay
Abhay

Reputation: 174

SaveFileDialog sfd = new SaveFileDialog()
{
    InitialDirectory = Application.StartupPath + "\\Scripts\\",
    Title = "Save Text Files",
    CheckPathExists = true,
    DefaultExt = "txt",
    Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
    FilterIndex = 1,
    RestoreDirectory = true
};

if (sfd.ShowDialog() == DialogResult.OK)
{
    File.WriteAllText(sfd.FileName, "your data here...");
}
  • You don't need to assign filename, if you know filename then no use of savefiledialog just directly use File.WriteAllText method with filename.
  • No need to check if file exists cause user might have to create new one
  • If you want to append text then use AppendAllText Method of File class.

Upvotes: 1

Related Questions