C#:我是否以正确的方式验证文件类型并使用goto?

Jie*_*eng 0 c#

我有保存文件的代码

SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text files|*.txt";

SaveDialog:
if ((bool)dialog.ShowDialog()) {
    if (System.IO.Path.GetExtension(dialog.FileName) != ".txt") {
        MessageBox.Show("You must select a .txt file");
        dialog.FileName = "";
        goto SaveDialog;
    }
    File.WriteAllText(dialog.FileName, txtEditor.Text);
}
Run Code Online (Sandbox Code Playgroud)

我读到我不应该使用goto.我可以使用do/while并检查是否选择了有效的扩展名,但这将添加许多不必要的代码.我觉得这个整洁.还是有更好/更正确的方法?

Nis*_*sim 5

using (SaveFileDialog dialog = new SaveFileDialog())
{
    dialog.Filter = "Text files|*.txt";
    while(dialog.ShowDialog() == DialogResult.OK)
        if (System.IO.Path.GetExtension(dialog.FileName).ToLowerInvariant() != ".txt")
            MessageBox.Show("You must select a.txt file");
        else // file is ok
        {
            File.WriteAllText(dialog.FileName, txtEditor.Text);
            break;
        }
 }
Run Code Online (Sandbox Code Playgroud)