开发一个“记事本”程序,要求能够实现文件的新建、打开、编辑、保存功能
(注意:资源的释放,可以使用OpenFileDialog和SaveFileDialog控件或者类)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace recordbook
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.ShowDialog();
string path = folder.SelectedPath;
string name = "\\" + "aa.txt";
if (!File.Exists(path + name))
{
FileStream fs1 = new FileStream(path + name, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs1);
MessageBox.Show("创建成功!");
sw.Close();
fs1.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "打开(Open)";
ofd.FileName = "";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//为了获取特定的系统文件夹,可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举,其中可以定义要返回路径的哪个系统目录
ofd.Filter = "文本文件(*.txt)|*.txt";
ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
ofd.CheckFileExists = true; //验证路径有效性
ofd.CheckPathExists = true; //验证文件有效性
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
this.richTextBox1.Text = sr.ReadToEnd();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void openFileDialog2_FileOk(object sender, CancelEventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
public void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "d:\\";
saveFileDialog1.Filter = "ext files (*.txt)|*.txt|All files(*.*)|*>**";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
DialogResult dr = saveFileDialog1.ShowDialog();
if (dr == DialogResult.OK && saveFileDialog1.FileName.Length > 0)
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
MessageBox.Show("存储文件成功!", "保存文件");
}
}
}
}
新建txt文件