/*
* 启动窗体后,单击“保存文件”,打开“保存”对话框,将richTextBox里保存的文件保存到指定位置。
* 单击“打开文件”菜单,将指定的文件内容读取到rithTextBox里。
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void 打开文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = openFileDialog1.FileName;
this.richTextBox1.Text=RWFFilebyFileStream.Read(filename);
MessageBox.Show("打开成功");
}
}
private void 保存文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
RWFFilebyFileStream.Write(filename, this.richTextBox1.Text.Trim());
MessageBox.Show("保存成功");
}
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
public class RWFFilebyFileStream
{
public static void Write(string strFile, string strText)
{ //利用FileStream写文件
FileStream fs = new FileStream(strFile, FileMode.Append, FileAccess.Write);
UTF8Encoding tmp = new UTF8Encoding();
byte[] b = tmp.GetBytes(strText);
fs.Write(b, 0, b.Length); //将内容写入文件中
fs.Dispose();
}
public static string Read(string strFile)
{
FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long i = fs.Length;
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length); //将文件内容读取到字节数组b中
fs.Dispose();
UTF8Encoding tmp = new UTF8Encoding(); //UTF8是一种编码模式,能将字节流转换为字符串
return tmp.GetString(b);
}
}
}
运行结果:
/*
* 利用StreamReader类,读取文件内容并显示在ritchTextBox控件中。
* 利用StreamWriter类,将ritchTextBox控件中内容写入文件。
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
textBox1.Text = fileName;
StreamReader sr=new StreamReader(fileName,Encoding.GetEncoding("gb2312"));
string line;
while ((line=sr.ReadLine())!=null) //读入文件下一行不为空
{
this.richTextBox1.Text += line + "\r\n"; //读一行,换行
}
sr.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog()==DialogResult.OK)
{
string fileName = saveFileDialog1.FileName;
textBox1.Text = fileName;
StreamWriter sw = new StreamWriter(fileName); //制定写入流
sw.Flush(); //清理缓冲区
//写入内容
sw.BaseStream.Seek(0, SeekOrigin.Begin);
sw.Write(richTextBox1.Text); //将richTextBox内容写入文件
sw.Close();
}
}
}
}
运行结果: