简体   繁体   中英

C#: Am i validating filetype and using goto in a right manner?

i have code to save a file like

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

i read that i should not use goto. i could use do/while and check that a valid extension was selected but that will add alot of unnecessary code. i find this neater. or is there a better/more correct way?

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

I would suggest the following:

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

    while (true) {
        if (dialog.ShowDialog() == DialogResult.OK) {
            if (!System.IO.Path.GetExtension(dialog.FileName).Equals(".txt", StringComparison.InvariantCultureIgnoreCase)) {
                MessageBox.Show("You must select a .txt file");
            }
            else {
                File.WriteAllText(dialog.FileName, txtEditor.Text);
                break; 
            }          
        }
        else break;
    }
}

While there are legitimate reasons for using the goto statement, in this case it can be avoided and replaced with a more readable solution.

Note also that you should not cast DialogResult (the return value of ShowDialog()) to bool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM