c# - 加载任何名称的第一张图像,解决异常错误,将丢弃的图像复制到文件夹
问题描述
我有一个从我的应用程序位置的子文件夹加载其默认 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]);
}
如何改进上述代码,以便在子文件夹不包含图像时不会出现异常“数组外的索引边界”?
在这种情况下不会出现异常错误 - 有没有办法让下一个图像拖放到该区域以将其作为新的默认图像自动复制到子文件夹中,每次表单运行并且子文件夹中没有图像时?
解决方案
您实际上可以使用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);
推荐阅读
- google-sheets - 如何附加到电子表格中的工作表
- docker - 命令 eval $(minikube docker-env) 不起作用,因为错误提示“无法连接到 docker daemon”
- excel - 仅在适用的情况下显示项目描述——如何在 Excel 中没有多个嵌套 IF 函数的情况下做到这一点?
- regex - 打击点。在组 []
- mysql - 存储过程问题无法正常工作
- python - 如何在 Python 中使用此错误处理?
- elasticsearch - Elasticsearch 地理查询显示没有结果
- android - Android 应用内更新在手机共享 wifi 时询问 Wifi
- python - 用户需要移动鼠标来发射子弹
- html - Angular 项目,在保存新对象/数据期间禁用添加图标