在c#中从本地磁盘加载和检查映像

本文关键字:加载 检查 映像 磁盘 | 更新日期: 2023-09-27 17:49:55

我正在尝试从本地磁盘加载图像,并且它正在工作。但我的问题是,我想检查图像是否在文件夹中可用,如果没有-然后消息框。显示("没有形象!");

加载图片:

 Bitmap bitmap1 = new Bitmap(@"Documentation''Pictures''"+table[8]+".jpg");
 pictureBox.Image=bitmap1;

在c#中从本地磁盘加载和检查映像

您可以使用File。Exists方法检查给定文件是否存在:

var file = Path.ChangeExtension(table[8], ".jpg");
var fullPath = Path.Combine(@"Documentation'Pictures", file);
if (!File.Exists(fullPath))
{
    MessageBox.Show("No image!");
}
else
{
    pictureBox.Image = new Bitmap(fullPath);
}

尝试使用File.Exists方法来测试文件本身是否存在。但是请注意,在调用该方法和调用实际加载文件的方法之间,文件可能已经消失了。因此,尽管如此,还是应该使用异常处理。

试试这个

string fileName = string.Format(@"Documentation''Pictures''{0}.jpg",table[8]);
if(!File.Exists(fileName))
{
MessageBox.Show("No Image");
}
else
{
Picture1.Image = Image.FromFile(fileName);
}