如何使用 OpenFileDialog 将文件路径正确格式化为字符串?

How to correctly format a filepath as a string with an OpenFileDialog?

在我的 Windows 应用程序中有一个 ListView。此 ListView 中的每个项目都有一些子项目,其中一个用于存储图像的文件路径。

每当 ListView 中的项目被 selected 时,PictureBox 中的图像就会用以下代码更新;

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    //check that only one item is selected
    if (listView1.SelectedItems.Count == 1)
    {
        //update the image from the filepath in the SubItem
        pictureBox1.Image = Image.FromFile(listView1.SelectedItems[0].SubItems[1].Text);
    }
}

一切正常。但是,当单击 PictureBox 时,它会打开一个 OpenFileDialog 以允许用户 select 图像。然后它将 ListView 中当前 selected 项的 SubItem.Text 更改为图像的文件路径,如下所示;

private void pictureBox1_Click(object sender, EventArgs e)
{
    //open a file dialog to chose an image and assign to the SubItem of the selected item
    openFileDialog1.ShowDialog();
    openFileDialog1.FileName = "";
    string Chosen_File = "";
    Chosen_File = openFileDialog1.FileName;
    listView1.SelectedItems[0].SubItems[1].Text = Chosen_File;
}

但是,当文件路径分配给 Chosen_File 时,它的格式不正确,这意味着当我 select 项目时我得到一个 ArgumentException。

为什么文件路径格式不正确,分配给 Chosen_File 时如何确保格式正确?

您应该更改代码以不从 OpenFileDialog 中删除选择,并且您还需要处理用户选择对话框上的取消按钮

private void pictureBox1_Click(object sender, EventArgs e)
{
    // Enter the assignment code only if user presses OK
    if(DialogResult.OK == openFileDialog1.ShowDialog())
    {
        // This is you error
        // openFileDialog1.FileName = "";
        string Chosen_File = openFileDialog1.FileName;
        listView1.SelectedItems[0].SubItems[1].Text = Chosen_File;
    }
}