c#制作的记事本的打开、新建、保存、另存功能

      private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
        {
   
            openFileDialog1.Title = "打开文件";
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            string FileName = ofd.FileName;

            if(File.Exists(FileName))
            {
                FileStream fs = new FileStream(FileName,FileMode.Open);
                StreamReader sr = new StreamReader(fs, Encoding.Default);//读取文件,其中‘Encoding.Default’为解决乱码问题
                richTextBox1.Text = sr.ReadToEnd();
                sr.Close();
                fs.Close();
            }
            else
            {
                MessageBox.Show("请选择有效的文件类型打开!!");
            }
        }

        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";//注意保存时要在文件名后面写明矿长名格式
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.ShowDialog();
            string FileName = sfd.FileName;

            FileStream fs = new FileStream(FileName, FileMode.Create);
            openFileDialog1.Title="保存";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);//把文件写入
                sw.Write(richTextBox1.Text);//写入新的文字
                sw.Close();//关闭操作器
                fs.Close();//关闭文件流
            }
           
            this.Text=saveFileDialog1.FileName;
        }

        private void 新建NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
     
           

        }

        private void 另存为AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = "";
            saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
          

     saveFileDialog1.InitialDirectory = Application.StartupPath;
     saveFileDialog1.Title = "另存为";
     if (saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
         sw.Write(richTextBox1.Text);
         sw.Close();
      }
     this.Text = saveFileDialog1.FileName;

        }

        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

你可能感兴趣的:(c#制作的记事本的打开、新建、保存、另存功能)