首先加入几个控件,两个分组空间,一个文本框,三个按钮,一个richTextBox控件,用于写入信息,布局如下:
下面是代码:
//保存文件路径的全局变量
private static string Depath = "";
首先创建文件
if (textBox1.Text.Length < 0)
{
MessageBox.Show("输入文件信息");
}
else
{
Depath = @"" + textBox1.Text.Trim() + "";
if (File.Exists(Depath)) MessageBox.Show("文本文件已存在,请重新命名");
else
{
StreamWriter sw = File.CreateText(Depath);
MessageBox.Show("文件已创建");
sw.Close();
}
}
保存文件信息
Depath = textBox1.Text.Trim();
FileStream file = File.Open(Depath,FileMode.OpenOrCreate,FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(file,Encoding.UTF8);
sw.Write(richTextBox1.Text.ToString());
MessageBox.Show("文件写入成功");
sw.Close();
打开文件编辑框,这里用到OpenFileDialog,代码如下:
try
{
//打开文件对话框
OpenFileDialog op = new OpenFileDialog();
op.Title = "打开文本文件";
op.FileName = "";
op.AddExtension = true;//检查文件扩展名
op.CheckFileExists = true;//指定文件是否存在
op.CheckPathExists = true;//检测路径合法性
op.Filter = "文本文件(*.txt)|*.txt";
op.ValidateNames = true;//接受有效的文件名
//判断是否点击了确定按钮
if (op.ShowDialog() == DialogResult.OK) {
StreamReader sr = new StreamReader(op.FileName,Encoding.Default);
this.richTextBox1.Text = sr.ReadToEnd();
textBox1.Text = op.FileName;
sr.Close();
}
MessageBox.Show("文件打开成功");
}
catch (Exception e1)
{
MessageBox.Show("错误"+e1.ToString());
}
好了,简单的小示例基本完成,但要注意一点,每做完一个文件操作都必须把读写器关闭,否则会提示进程占用;
**上述代码还需注意一点,容易忘记;当打开文件时候,要把路径变量赋值,即
textBox1.Text = op.FileName;
Depath = textBox1.Text.Trim();
不然保存编辑的文本时 Depath是空值;**