c# - 过滤文件扩展名的 if 语句 (C#)
问题描述
我想继续创建一个程序,该程序使用不同的文件扩展名执行不同的事件,文件以 . 我理解 Path.GetExtension 之类的东西,以及这些答案:重构 if-else statements 检查不同的文件扩展名 C# custom file extension filter
有人可以直接向我解释如何创建一个按钮“If Statement”,意思是执行说,如果检测到“.jpeg”文件作为所选文件的扩展名,而“else”可能会弹出消息框,例如“Improper File”类型已上传。”
这是发生动作的代码片段:
private void BtnMediaPlayer_Click(object sender, EventArgs e)
{
// Open File Dialog
OpenFileDialog open = new OpenFileDialog();
// Image Filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
}
}
可以看出,该程序打开一个打开文件对话框,然后应该过滤某些文件,然后在 pciture 框中打开它们,但我该如何重写它,“if (open.ShowDialog() == DialogResult.OK)"或周围的代码会根据文件类型产生不同的结果(基于 If 语句的执行)?
TL DR 如何为上传的不同文件编写 If 语句?
解决方案
private void BtnMediaPlayer_Click(object sender, EventArgs e)
{
var ofd = new OpenFileDialog();
ofd.Filter = OpenFileImageFilter;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (IsValidImageFile(ofd.FileName))
{
// display image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
}
else
{
MessageBox.Show("Invalid file type selected.");
}
}
}
// array of image formats so we can use it in OpenFileDialog filter
// and in our IsValidImageFile method
private string[] ImageFormats => new[] { ".jpg", ".jpeg", ".gif", ".bmp" };
// helper method to turn array of image extensions into OpenFileDialog filter string
private string OpenFileImageFilter
{
get
{
string fileExts = "";
foreach (string s in ImageFormats)
{
fileExts += $"*{s};";
}
return $"Image Files({fileExts})|{fileExts}";
}
}
// reusable method that uses the ImageFormats property to check file extension
private bool IsValidImageFile(string filename)
{
if (string.IsNullOrEmpty(filename)) return false;
string extension = Path.GetExtension(filename);
return ImageFormats.Contains(extension);
}
推荐阅读
- html - 受内容图像宽度百分比影响的网格元素高度
- dart - 如何在小部件类中使用 switch 语句
- quarkus - 是否可以从 Maven 存储库中获取任何库并用于 Quarkus 应用程序
- android - 带有自定义拇指和间隔文本 Android 的 Seekbar
- sql - 如何从 PostgreSQL 中的 WITH 返回 EXCLUDED?
- css - PrimeNG v10.0.0,当 [responsive]='true' 并且网格响应时,p-table 页脚消失
- python - Python OpenCV.fillPoly() 没有填充我的多边形。为什么?
- python - 在 Python 3.8 中加载使用 Python 2.7 创建的泡菜文件时出错
- c# - 文件解析以获取特定信息
- jenkins - JENKINS - GROOVY - PIPELINE:如何在构建过程中检索密码时从日志中隐藏密码