首页 > 解决方案 > 加载任何名称的第一张图像,解决异常错误,将丢弃的图像复制到文件夹

问题描述

我有一个从我的应用程序位置的子文件夹加载其默认 BgImage 的表单。
当默认的 BackgroundImage 可见时,它可以用作其他常见位图格式的放置区域(从 Windows 资源管理器拖放图像)。
如果子文件夹中有图片,则将文件夹中第一个位置的图片加载为默认的BackgroundImage。

string path = (full path to folder here, @"image_default\");
string[] anyfirstimage = Directory.GetFiles(path);

if (String.IsNullOrEmpty(anyfirstimage[0]))
{
    // do nothing
}
else
{
    this.BackgroundImage = Image.FromFile(anyfirstimage[0]);
}

如何改进上述代码,以便在子文件夹不包含图像时不会出现异常“数组外的索引边界”?
在这种情况下不会出现异常错误 - 有没有办法让下一个图像拖放到该区域以将其作为新的默认图像自动复制到子文件夹中,每次表单运行并且子文件夹中没有图像时?

标签: c#winformsloadimage

解决方案


您实际上可以使用Application.ExecutablePath来获取可执行路径。然后轻松检查其中的文件数是否大于零。

string path=Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"image_default");
string[] anyfirstimage = Directory.GetFiles(path, "*.jpg");
if(anyfirstimage.Length > 0) BackgroundImage = Image.FromFile(anyfirstimage[0]);

如果可能有除图像以外的其他文件,请确保使用GetFiles()类似的模式重载Directory.GetFiles(path, "*.jpg")以确保未选择其他文件格式。

作为您评论的答案,搜索模式不接受多种模式,但您可以稍后过滤它们,例如:

var anyfirstimage = Directory.GetFiles(path).Where(x=> {var l = x.ToLower();
return l.EndsWith(".jpg") || l.EndsWith(".png") || l.EndsWith(".gif");}).ToArray();

最后,代码应该是这样的:

string path=Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"image_default");
 string anyfirstimage = Directory.GetFiles(path).Where(x=> {var l = x.ToLower();
  return l.EndsWith(".jpg") || l.EndsWith(".png") || l.EndsWith(".gif");}).FirstOrDefault();
if(anyfirstimage != null) BackgroundImage = Image.FromFile(anyfirstimage);

推荐阅读