首页 > 解决方案 > 过滤文件扩展名的 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 语句?

标签: c#imageif-statementpictureboxfile-extension

解决方案


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


推荐阅读