System.IO.FileNotFoundException 当文件存在并授予权限时

本文关键字:权限 存在 IO FileNotFoundException 文件 System | 更新日期: 2023-09-27 18:37:15

运行此代码时出现System.IO.FileNotFoundException错误。我是否在代码中做了一些严重的错误,或者是否有一些我还没有想到的小事情?

我已经确保所有内容都有权限,并且文件肯定存在并且文件类型正确。

public Form1()
{
    InitializeComponent();
    DirectoryInfo ImgD = new DirectoryInfo("C:/Users/Dan/ImgDirectory/");
    FileInfo[] rgFiles = ImgD.GetFiles("*.jpg");
    foreach (FileInfo fi in rgFiles)
    {
        listBox1.Items.Add(Path.GetFileNameWithoutExtension(fi.Name));
    }
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    pictureBox1.Image = System.Drawing.Image.FromFile(
        @"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString());
}

System.IO.FileNotFoundException 当文件存在并授予权限时

您正在使用不带扩展名的文件名填充列表框。

因此,在此行中,您需要再次附加扩展名:

pictureBox1.Image = System.Drawing.Image.FromFile(@"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString());

所以它变成了这样:

pictureBox1.Image = System.Drawing.Image.FromFile(@"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString() + ".jpg");

作为旁注,如果使用调试断点,则可以轻松检测到此类错误。由于该行是给您带来麻烦的那一行,因此您应该在那里放置一个断点并启动调试 (F5)。当代码在该断点处停止时,您可以检查 @"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString()) 的值,您会发现问题所在。