2014年11月27日 星期四

[C#]開啟及瀏覽檔案並寫回TextBox實例

參考了這兩篇
Microsoft Developer Network - OpenFileDialog 類別

How to open file .txt with using openFileDialog in c#?


using System.IO;

...略...

//新增一個Button叫做Firm_Open並對其button點擊兩下以進入編輯 點擊事件
private void Firm_Open_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "c:\\";

/*OpenFileDialog.Filter = "Audio files (*.wav; *.mpa; *.mp2; *.mp3; *.au; *.aif; *.aiff; *.snd; *.wma)|*.wav; *.mpa; *.mp2; *.mp3; *.au; *.aif; *.aiff; *.snd; *.wma|" + "Video Files (*.avi; *.qt; *.mov; *.mpg; *.mpeg; *.m1v; *.wmv)|*.avi; *.qt; *.mov; *.mpg; *.mpeg; *.m1v; *.wmv|" + "MIDI Files (*.mid, *.midi, *.rmKKTimeri)|*.mid; *.midi; *.rmi|" + "Image Files (*.jpg, *.bmp, *.gif, *.tga)|*.jpg; *.bmp; *.gif; *.tga|" + "All Files (*.*)|*.*";
      OpenFileDialog.Title = "請開啟語音檔";
      OpenFileDialog.Multiselect = true; // 允許選取多檔案
*/


            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            string file = Path.GetFullPath(openFileDialog1.FileName);
                            DL2_FIRM_BOX.Text = file;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:Open file error: " + ex.Message);
                }
            }
        }

沒有留言:

張貼留言