【问题标题】:Loading and checking image from local disk in C#在 C# 中从本地磁盘加载和检查图像
【发布时间】:2011-04-10 22:26:31
【问题描述】:

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

加载图片:

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

【问题讨论】:

  • 您不应将@\\ 结合使用。
  • 而且您还应该验证文件是否名称为 Picutre.png 但它不是 Picutre,搜索特定的异常!
  • 当您使用@ 符号时,您可以使用在资源管理器中显示的路径。您不再需要转义斜线。

标签: c# .net image


【解决方案1】:

您可以使用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);
}

【讨论】:

  • ASP.NET最好是Server.MapPath("Documentation/Pictures"),否则它会在Windows的系统文件夹中寻找文件.. :)
  • @Shadow Wizard,是的,绝对的,事实上在 ASP.NET 中它应该是:Server.MapPath("~/Documentation/Pictures")
  • @Shadow Wizard,你在说什么 ASPX?在 OP 中看不到任何关于 ASP.NET 的参考。更别提pictureBox和ASP.NET了,嗯……
  • @Darin:你能详细说明你为什么使用 Path.ChangeExtension 吗?有什么具体原因吗?
  • @Sergio,它更安全,在处理诸如 Path.Combine、Path.ChangeExtension 等文件时,我总是使用文件特定的函数,而不是字符串连接。例如,如果 table[8] 以点 (.) 结尾,则该函数将正确处理这种情况,而如果您使用字符串连接,则可能以 foo..jpg 结尾。
【解决方案2】:

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

更多信息请参见this link

【讨论】:

    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 2022-06-27
      • 2019-08-17
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多