C#—文件操作—实验12.3

来源:互联网 发布:matlab矩阵中有未知数 编辑:程序博客网 时间:2024/06/14 07:42
/* * 要求: * 第一次单击“保存”时,弹出一个对话框,并将内容保存到指定的文件夹中;以后再单击“保存”按钮,自动将最新内容保存下来,不再弹出对话框。 */using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.IO;using System.Windows.Forms;namespace WindowsFormsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {        }        private string fileName;        private bool f = true;        private void button1_Click(object sender, EventArgs e)        {            if (f)            {                if (saveFileDialog1.ShowDialog() == DialogResult.OK)                {                    fileName = saveFileDialog1.FileName;                    StreamWriter sw = new StreamWriter(fileName);        //制定写入流                    sw.Flush();            //清理缓冲区                    //写入内容                    sw.BaseStream.Seek(0, SeekOrigin.Begin);                    sw.Write(richTextBox1.Text);          //将richTextBox内容写入文件                    f = false;                    sw.Close();    //此句必须有,否则保存为空,不知道为什么                }            }            else            {                StreamWriter sw = new StreamWriter(fileName);                sw.Flush();                 sw.BaseStream.Seek(0, SeekOrigin.Begin);                sw.Write(richTextBox1.Text);          //将richTextBox内容写入文件                sw.Close();            }        }        private void button2_Click(object sender, EventArgs e)        {            Application.Exit();        }        }}


运行结果:

0 0
原创粉丝点击