Save file to specific folder in C# using SaveFileDialog

10.5k Views Asked by At

I need to save a file using SaveFileDialog to a specific folder.

For example, say we want to save in "c:\MyNewFolder". If the folder doesn't exist, create it and save there, or only save there if the folder does exist.

String fileName="";
String date = DateTime.Now.Day+"-"+DateTime.Now.Month+"-"+DateTime.Now.Year;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    using (Stream s = File.Open(saveFileDialog1.FileName,FileMode.CreateNew))
    using (StreamWriter sw = new StreamWriter(s))
    {
        sw.WriteLine(tbName.Text);
        sw.WriteLine(tbSummary.Text);
    }
}
2

There are 2 best solutions below

4
On

You can look for

SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "c:\\MyNewFolder";
save.RestoreDirectory = true;
1
On
string strPath="c:\MyNewFolder";

if (!Directory.Exists(strPath))

{

    Directory.CreateDirectory(strPath);

}

else

{

//Continue your logic and append your file name

}