赞
踩
C# winform的程序内用openfiledialog来打开对话框选择文件, 用savefiledialog来打开对话框显示要存储的文件名和文件路径
程序代码如下:
- private void button2_Click(object sender, EventArgs e)
- {
- OpenFileDialog ofldg = new OpenFileDialog();
- ofldg.Title = "选择需要打开的文件";
- ofldg.Filter = "Txt(*.txt)|*.txt";
- ofldg.InitialDirectory = @"D:\";
- if (ofldg.ShowDialog() == DialogResult.OK)
- {
- string filename = ofldg.FileName;
- textBox2.Text = filename;
- try
- {
- // 创建一个 StreamReader 的实例来读取文件
- // using 语句也能关闭 StreamReader
- StreamReader streamReader = new StreamReader(filename);
- //判断文件中是否有字符
- while (streamReader.Peek() != -1)
- {
- //读取文件中的一行字符
- string str = streamReader.ReadToEnd();
- textBox1.Text = str ;
-
-
- }
- streamReader.Close();
-
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- SaveFileDialog sflg = new SaveFileDialog();
- sflg.Filter = "Txt(*.txt)|*.txt";
- if(sflg.ShowDialog() == DialogResult.OK)
- {
- textBox2.Text = sflg.FileName;
- StreamWriter swriter = new StreamWriter(sflg.FileName, true);
- swriter.Write(textBox1.Text);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。