C#中SaveFileDialog和OpenFileDiaLog 用法

  • Post author:
  • Post category:其他




C#中SaveFileDialog和OpenFileDiaLog 用法

介绍SaveFileDialog以及OpenFileDiaLog的使用,把textbox中的内容通过SaveFileDialog保存到文件中。

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;
using System.IO;

namespace SaveFileDialog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            StreamWriter myStream;
            saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";//设置文件类型 
            saveFileDialog1.FilterIndex = 1;//设置默认文件类型显示顺序
            saveFileDialog1.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录
            //点了保存按钮进入
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                myStream = new StreamWriter(saveFileDialog1.FileName);
                myStream.Write(textBox1.Text); //写入
                myStream.Close();//关闭流
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "文本文件|*.txt";// 指定打开文本文件(后缀名为txt)
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                string[] lines = File.ReadAllLines(openDlg.FileName);// 读出文本文件的所以行
                textBox1.Clear();// 先清空textBox1
                // 在textBox1中显示
                foreach (string line in lines)
                {
                    textBox1.AppendText(line + Environment.NewLine);
                }
                // 显示文件路径名
            }
        }
    }
}



版权声明:本文为weixin_43595119原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。