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

Elf*_*foc 1 .net c# image

我正在尝试从本地磁盘加载图像,它正在工作.但我的问题是,我想检查文件夹中是否有图像,如果没有 - 那么MessageBox.Show("No image!");

载入图片:

 Bitmap bitmap1 = new Bitmap(@"Documentation\\Pictures\\"+table[8]+".jpg");
 pictureBox.Image=bitmap1;
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • @Sergio,它更安全,在处理Path.Combine,Path.ChangeExtension等文件时,我总是使用特定于文件的函数,而不是字符串连接.例如,如果`table [8]`以点(`.`)结尾,则该函数将正确处理该情况,而如果您使用字符串连接,则可能最终得到`foo..jpg`. (2认同)