【程式設計】【C#】使用OpenFileDialog來開啟文字檔案
程式專案下載:openTextFile
程式中的元件:
1.OpenFileDialog
2.Button
3.TextBox,名稱設寫tbResult,多行,垂直scrollbar
程式碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 建立一個OpenFileDialog物件 OpenFileDialog openFileDialog1 = new OpenFileDialog(); // 設定OpenFileDialog屬性 openFileDialog1.Title = "選擇要開啟的文字檔案"; openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.Multiselect = true; // 喚用ShowDialog方法,打開對話方塊 if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string theFile = openFileDialog1.FileName; //取得檔名 Encoding enc = Encoding.GetEncoding("big5"); //設定檔案的編碼 tbResult.Text = System.IO.File.ReadAllText(theFile, enc); //以指定的編碼方式讀取檔案 } } } }