试图通过 Openfiledialog 获取文件路径

Trying to get filepath through Openfiledialogue

我正在编写按钮点击代码,使用文件对话框打开文件,我可以从中选择图片。然后我想提取文件的路径并将其存储在一个字符串变量中并将其作为参数传递(此处编译器抛出异常:"A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll,Additional information: OK"),至于我的代码我需要动态路径以便每次相似的图片都不会没出现..

//从文件中选择图片
public void select_image_button17_Click(object sender, EventArgs e) {

            foreach (Button b in game_panel1.Controls)
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                 openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
                string a = "";
                a = openFileDialog1.ShowDialog().ToString();
                string directoryPath = Path.GetDirectoryName(a);

                Image ToBeCropped = Image.FromFile(a,true);//exception
                ReturnCroppedList(ToBeCropped, 320, 320);
                pictureBox1.Image = ToBeCropped;
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                AddImagesToButtons(images);

            }
    }

FileName 属性 将在对话框 returns 处于 OK 状态时设置。

if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
    // User cancelled out of dialog
}
else
{
    string filename = openFileDialog1.FileName;
}