C#中SaveFileDialog和OpenFileDiaLog 用法

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);
                }
                // 显示文件路径名
            }
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值