加载任何名称的第一张图像,解决异常错误,将拖放的图像复制到文件夹

Load first image with any name, solve exception error, copy dropped image to folder

我有一个从我的应用程序所在位置的子文件夹加载其默认 BgImage 的表单。
当默认的 BackgroundImage 可见时,它可以用作其他常见位图格式的放置区域(从 Windows Explorer 拖放图像)。
如果子文件夹中有任何图像,位于文件夹中第一个位置的图像将作为默认背景图像加载。

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

我怎样才能改进上面的代码,这样我就不会得到异常 'Index bounds outside the array' 当子文件夹不包含图像时?
在这种情况下,不是出现异常错误 - 有没有办法将下一个图像拖放到该区域以将其作为新的默认图像自动复制到子文件夹中, 每次运行表单时,子文件夹中都没有图像?

其实可以用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);