1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.IO; 11 using System.Security; 12 13 namespace OpenFile 14 { 15 public partial class OpenFileDialogForm : Form 16 { 17 // 字段 18 private Button selectButton; // 按钮 19 private OpenFileDialog openFileDialog1; // 打开文件对话框 20 private TextBox textBox1; // 文本编辑框 21 22 //窗体构造函数 23 public OpenFileDialogForm() 24 { 25 //新建打开文件对话框 26 openFileDialog1 = new OpenFileDialog(); 27 28 //新建按钮 29 selectButton = new Button 30 { 31 Size = new Size(100, 20), 32 Location = new Point(15, 15), 33 Text = "Select file" 34 }; 35 36 //添加, 按钮Click事件处理 37 selectButton.Click += new EventHandler(SelectButton_Click); 38 39 //新建文本编译框 40 textBox1 = new TextBox 41 { 42 Size = new Size(300, 300), 43 Location = new Point(15, 40), 44 Multiline = true, 45 ScrollBars = ScrollBars.Vertical 46 }; 47 48 //窗体大小 49 ClientSize = new Size(330, 360); 50 51 //窗体容器, 添加按钮、文本编译框 52 Controls.Add(selectButton); 53 Controls.Add(textBox1); 54 } 55 56 //文本复制 57 private void SetText(string text) 58 { 59 textBox1.Text = text; 60 } 61 62 //按钮Click事件处理函数 63 private void SelectButton_Click(object sender, EventArgs e) 64 { 65 if (openFileDialog1.ShowDialog() == DialogResult.OK) 66 { 67 try 68 { 69 //新建读取文件流对象 70 var sr = new StreamReader(openFileDialog1.FileName); 71 //文本复制 72 SetText(sr.ReadToEnd()); 73 } 74 catch (SecurityException ex) 75 { 76 MessageBox.Show("Security error.\n\nError message: {ex.Message}\n\n" + 77 "Details:\n\n{ex.StackTrace}"); 78 } 79 } 80 } 81 } 82 }