How can I prevent an exception when I cancel an op

2019-02-21 17:04发布

问题:

My program has a button which when clicked opens an openfiledialog to choose a picture:

private string ChoosePicture()
{         
    fDialog.Title = "Select Picture";
    fDialog.Filter = "Image Files (*.bmp, *.gif, *.jpg)|*.bmp; *.gif*;*.jpg";
    fDialog.InitialDirectory = "C:";
    fDialog.ShowDialog();

    fDialog.AddExtension = true;
    fDialog.CheckFileExists = true;
    fDialog.CheckPathExists = true;

    //returns a string for the directory
    return fDialog.FileName.ToString();
}

Using a check on the dialogresult box hasn't resolved my issue either:

fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;

DialogResult res = fDialog.ShowDialog();
if (res == DialogResult.OK)
{                
    //returns a string for the directory
    return fDialog.FileName.ToString();
}

return null; 

The code works if I do choose a picture and complete the file selection. However if I cancel the process at any point in between I get the exception "The path is not of a legal form". I am not sure which part I imagine I could take care of this with a try-catch, however I'm not positive which part is causing the issue? If I put a try catch around the call to the ChoosePicture() method, I can at least stop it from crashing the program but the exception is still being thrown when no picture is selected in the fdialogbox.

回答1:

DialogResult result = fileDialog.ShowDialog();
if (result == DialogResult.OK) {

     //returns a string for the directory
     return fDialog.FileName;
}

return null; //not sure what you will return if they cancel

also, FileName is already a string, so no need to use .ToString() on it

EDIT: fixed indenting



回答2:

Check the dialog result and act accordingly:

private string ChoosePicture()
{         

        fDialog.Title = "Select Picture";
        fDialog.Filter = "Image Files (*.bmp, *.gif, *.jpg)|*.bmp; *.gif*;*.jpg";
        fDialog.InitialDirectory = "C:";
        DialogResult res = fDialog.ShowDialog();

        if(res == DialogResult.OK)
        {
           fDialog.AddExtension = true;
           fDialog.CheckFileExists = true;
           fDialog.CheckPathExists = true;

           //returns a string for the directory
           return fDialog.FileName.ToString();
        }            
        else
        {
           return null; // or something
        }
}


回答3:

Test to see if a file was selected:

   fDialog.ShowDialog();
   if (!string.IsNullOrEmpty(fDialog.FileName))
   {
        fDialog.AddExtension = true;
        fDialog.CheckFileExists = true;
        fDialog.CheckPathExists = true;

        //returns a string for the directory
        return fDialog.FileName.ToString();
    } else {
        return String.Empty;
    }


回答4:

DialogResult dresult=fDialog.ShowDialog();

Check if dresult==DialogResult.Ok and only after proceed with file operations.



回答5:

fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
DialogResult res = fDialog.ShowDialog();
        if (res == DialogResult.OK)
        {            
            //returns a string for the directory
            return fDialog.FileName.ToString();
        }
        return null; 

Now it will work !

We should add properties to the dialogbox before its actually been shown. So when it opens, it will have all these properties when you open them for the first time.

Edit :okay you have added to the designer by the toolbox already and its by default all of these options. but if some add from code. it should be always before its being shown. I will leave this here. so that someone who does this

this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();

in code, will know that they should do these property addition before showing the dialog. Again, these true values are by default so unless u have mentioned false before elsewhere and making it true here.



回答6:

You can just do it like this instead of return fDialog.FileName; and DialogResult.Cancel is a better option since your looking for a cancel and not for the OK result.

 DialogResult result = fDialog.ShowDialog();
                if (result == DialogResult.Cancel)
                {
                    return;
                }


回答7:

i added a boolean and check if file selected or not

    public Form1()
    {
        InitializeComponent();
    }
    bool fileSelected = false; //default false because nothing selected at start.
    private void Form1_Load(object sender, EventArgs e)
    {

    }
private void button1_Click(object sender, EventArgs e)
    {
        openFile();
        if (fileSelected == true)
        {
            codes...
        }
    }

    string path= "";
    private void openFile()
    {
        OpenFileDialog file= new OpenFileDialog();
        file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        file.Filter = "Text File|*.txt";
        //file.RestoreDirectory = true;
        if (file.ShowDialog() == DialogResult.OK)
        {
            path= dosya.FileName;
            fileSelected = true;
        }
        else
        {
            MessageBox.Show("File not selected.");
        }
    }

i prevent this error like that.