如图,点击选择文件则读取文件路径,读取时将文件内容显示到文本框中,写入时将文本框内容写入文件
View Code
namespace 文件操作
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open =new OpenFileDialog();
open.Filter ="*.txt|*.txt"; //文件类型
if (open.ShowDialog() == DialogResult.OK)
{
textBox1.Text = open.FileName;
}
}
/// <summary>
/// 读取文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length <0)
{
return;
}
Stream stream =new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
using (StreamReader reader =new StreamReader(stream, Encoding.Default))
{
string pp ="";
while (reader.Peek() >-1)
{
pp += reader.ReadLine();
}
richTextBox1.Text = pp;
}
}
/// <summary>
/// 写入文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
Stream stream =new FileStream(textBox1.Text, FileMode.Create, FileAccess.Write);
StreamWriter writer =new StreamWriter(stream, Encoding.Default);
writer.WriteLine(richTextBox1.Text);
}
}
}
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open =new OpenFileDialog();
open.Filter ="*.txt|*.txt"; //文件类型
if (open.ShowDialog() == DialogResult.OK)
{
textBox1.Text = open.FileName;
}
}
/// <summary>
/// 读取文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length <0)
{
return;
}
Stream stream =new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
using (StreamReader reader =new StreamReader(stream, Encoding.Default))
{
string pp ="";
while (reader.Peek() >-1)
{
pp += reader.ReadLine();
}
richTextBox1.Text = pp;
}
}
/// <summary>
/// 写入文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
Stream stream =new FileStream(textBox1.Text, FileMode.Create, FileAccess.Write);
StreamWriter writer =new StreamWriter(stream, Encoding.Default);
writer.WriteLine(richTextBox1.Text);
}
}
}