注:1)读写文本文件需要引用IO命名空间
2)读txt文件需要OpenFileDialog控件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//引用IO命名空间
using System.IO;
namespace TextReader
{
public partial class TextReader : Form
{
public TextReader()
{
InitializeComponent();
}
/// <summary>
/// 写入文本文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnWrite_Click(object sender, EventArgs e)
{
string path = txtFilePath.Text;//路径
string content = txtContent.Text;//内容
if (path.Equals(null) || path.Equals(""))
{
MessageBox.Show("文件路径不能为空");
return;
}
try
{
//创建文件流
FileStream myfs = new FileStream(path, FileMode.Create);
//创建写入器
StreamWriter mySw = new StreamWriter(myfs);
//将录入的内容写入文件
mySw.Write(content);
//关闭写入器
mySw.Close();
//关闭文件流
myfs.Close();
MessageBox.Show("写入成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 读取文本文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRead_Click(object sender, EventArgs e)
{
//打开,需要OpenFileDialog控件
this.ofdMain.ShowDialog();
string path = ofdMain.FileName;
if (path.Equals(null) || path.Equals(""))
{
return;
}
//检测是否是文本文件(以.txt结尾)
string fileName = path.Substring(path.LastIndexOf("."));
if (!fileName.Equals(".txt"))
{
MessageBox.Show("请选择文本文件!", "提示");
return;
}
string content;
try
{
//创建文件流
FileStream myfs = new FileStream(path, FileMode.Open);
//创建读取器
StreamReader mySr = new StreamReader(myfs,Encoding.Default);
//读取文件所有内容
content = mySr.ReadToEnd();
txtContent.Text = content;
//关闭读取器
mySr.Close();
//关闭文件流
myfs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}