如果初始目录不存在,请创建它,但是如果用户取消保存,请删除新添加的文件夹

问题描述 投票:0回答:1

我想使用SaveFileDialog将文本框文本保存到在特殊目录中创建的.txt文件中。

但是我的路径不存在:我想当对话框出现时询问用户要将他的.txt文件保存在哪里,如果缺少这些文件夹,对话框会自动创建它们。但是我也喜欢这样,如果用户取消他的保存,则新创建的文件夹将在它们为空时删除。

换句话说:SaveFileDialog对话框显示在初始目录中,但是如果该初始目录为空,则我的代码生成该目录,但是如果用户取消,我的代码将擦除生成的目录。

这是我的示例:我想将.txt保存在Desktop \ FolderExistingOrNot中,但是如果文件夹FolderExistingOrNot我想创建它。但是,如果用户取消,如果FolderExistingOrNot为空,我想删除。

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
    }
}

这可能很简单,但是我还没有弄清楚该怎么做。

c# winforms savefiledialog
1个回答
0
投票

这在我测试时对我有用。

    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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.