c# 检查是否应用了任何图片
本文关键字:任何图 应用 检查 是否 | 更新日期: 2023-09-27 18:36:37
anq">我正在尝试显示用户选择的文件夹中的图像。如果他选择了没有任何图片的记录,它将显示一个名为
空的.png
这是我写的代码。我怎样才能改变它,让它符合我在解释中写的内容?(这个问题的顶部)
string[] fileEntries = Directory.GetFiles(@"C:'Projects_2012'Project_Noam'Files'ProteinPic");
foreach (string fileName in fileEntries)
{
if (fileName.Contains(comboBox1.SelectedItem.ToString()))
{
Image image = Image.FromFile(fileName);
// Set the PictureBox image property to this image.
// ... Then, adjust its height and width properties.
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
}
foreach (string fileName in fileEntries)
{
if (fileName.Contains(comboBox1.SelectedItem.ToString()))
{
pictureBox1.Image = Image.FromFile(fileName);
}
else
{
pictureBox1.Image = ImageFromFile("Empty.png");
}
// Set the PictureBox image property to this image.
// ... Then, adjust its height and width properties.
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
string[] fileEntries = Directory.GetFiles(@"C:'Projects_2012'Project_Noam'Files'ProteinPic");
if (fileEntries.Length == 0)
{
Image image = Image.FromFile("Path of empty.png");
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
else
{
foreach (string fileName in fileEntries)
{
if (fileName.Contains(comboBox1.SelectedItem.ToString()))
{
Image image = Image.FromFile(fileName);
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
}
}
我认为您不需要遍历目录中的每个文件来实现您想要的
Image image;
string imagePath = System.IO.Path.Combine(@"C:'Projects_2012'Project_Noam'Files'ProteinPic", comboBox1.SelectedItem.ToString());
if (System.IO.File.Exists(imagePath))
{
image = Image.FromFile(imagePath);
}
else
{
image = Image.FromFile(@"C:'Projects_2012'Project_Noam'Files'ProteinPic'Empty.png");
}
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;