为了账号安全,请及时绑定邮箱和手机立即绑定

多个过滤器 OpenFileDialog

多个过滤器 OpenFileDialog

C#
繁花如伊 2023-08-20 10:57:00
目前,我的表单上有三个按钮,每个按钮都会打开一个不同的表单(form2 带有一个文本框,用于显示文本文件中的文本,form3 带有一个图片框,用于显示图像)我想做的是将两者放在一起作为最后一个按钮,以便用户可以过滤要打开的类型(TXT 文件或图像文件)。我不确定如何将两者放在一起并让它们工作。我用来打开文本文件的代码: private void button1_Click(object sender, EventArgs e)        {            OpenFileDialog ofd = new OpenFileDialog();            ofd.InitialDirectory = @"C:\";            ofd.Filter = "TXT Files(*.txt;)|*.txt;";            if(ofd.ShowDialog() == DialogResult.OK)            {                using(StreamReader rdText = new StreamReader(ofd.FileName))                {                    string info = File.ReadAllText(ofd.FileName);                    TextDocumentForm newTextDocument = new TextDocumentForm();                    newTextDocument.TextFileName = info;                    newTextDocument.Show();                                 }            }        }我用什么来打开我的图像文件 private void button2_Click(object sender, EventArgs e)        {                          OpenFileDialog ofdi = new OpenFileDialog();                ofdi.InitialDirectory = @"C:\";                ofdi.Filter = "Image Files(*.jpg;*.jpeg;*.bmp)|*.jpg;*.jpeg;.bmp;";                if (ofdi.ShowDialog() == DialogResult.OK)                {                    Image image = Image.FromFile(ofdi.FileName);                    ImgDoc newImageDoc = new ImgDocumentForm();                    newImageDoc.ImageShow = image;                    newImageDoc.Show();                }                    }感谢任何帮助,因为我正在努力加深对 OpenFileDialog 仍然如何工作的理解。
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

组合过滤器:


var openFile = new OpenFileDialog

            {

                InitialDirectory = @"C:\",

                Filter = "TXT Files(*.txt;)|*.txt;|Image Files(*.jpg;*.jpeg;*.bmp)|*.jpg;*.jpeg;.bmp;"

            };

然后使用Path.GetExtension()查看您应该采取哪条路线:


if (openFile.ShowDialog() == true)

{

    var ext = System.IO.Path.GetExtension(openFile.FileName);

    if (ext == ".txt")

    {

        // Open text file

    }

    else if (ext == ".jpg" || ext == ".jpeg" || ext == ".bmp")

    {

        // Open image file

    }

}


查看完整回答
反对 回复 2023-08-20
  • 1 回答
  • 0 关注
  • 92 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信