c#检查是否有任何图片

时间:2012-06-08 10:03:04

标签: c# winforms picturebox

我正在尝试从用户选择的文件夹中显示图像。如果他选择了没有任何图片的记录,则会显示一个名为

的图像
  

Empty.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;
                }
            }

3 个答案:

答案 0 :(得分:2)

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;

}

答案 1 :(得分:1)

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;
                }
            }
        }

答案 2 :(得分:0)

我认为你不需要遍历目录中的每个文件来实现你想要的东西

        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;