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|*.开发者_JAVA技巧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.
精彩评论