亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

多個過濾器 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 關注
  • 190 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號