I want to save a textbox text to a .txt file created in a special directory, using a SaveFileDialog.
But let's say my path doesn't exist: I would like that when the dialogbox shows up to ask where the user want to save his .txt file, the dialogbox create automatically the missing folders if they are missing. But I also like that if the user cancel his saving, the newly created folder to erase if they are empty.
In other words: the SaveFileDialog dialogbox shows up in an initial directory, but if this initial directory is null, my code generate this directory BUT if the user cancel, my code erase the generated directory.
Here's my example: I want to save my .txt in Desktop\FolderExistingOrNot, but if the folder FolderExistingOrNot I want to creat it. But if the user cancels, I want to delete if FolderExistingOrNot is empty.
private void btn_SAVE_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "txt";
sfd.Filter = ".TXT (*.txt)|*.txt";
sfd.FileName = textBox1.Text;
sfd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\FolderExistingOrNot";
//Directory.CreateDirectory(sfd.InitialDirectory); // could use that but if the user cancel, this folder will not be destroyed
if (sfd.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(sfd.FileName, textBox2.Text);
}
else // if the user cancel the saving
{
// I would like to erase the folder FolderExistingOrNot if it's empty
}
}
It might be simple but I haven't figured out how to do it.
This worked for me when I tested it.
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "txt";
sfd.Filter = ".TXT (*.txt)|*.txt";
sfd.FileName = textBox1.Text;
string mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\FolderExistingOrNot";
Directory.CreateDirectory(mypath);
sfd.InitialDirectory = mypath;
//Directory.CreateDirectory(sfd.InitialDirectory); // could use that but if the user cancel, this folder will not be destroyed
if (sfd.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(sfd.FileName, textBox2.Text);
}
else // if the user cancel the saving
{
if (Directory.GetFiles(mypath).Length == 0)
{
Directory.Delete(mypath);
}
}