C#: 最简单的文件读写
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//浏览按钮点击事件
private void btnExplorer_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"d:/";
ofd.RestoreDirectory = true;//在关闭对话框前是否还原当前目录
ofd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK) {
txtPath.Text = ofd.FileName;
//创建文件流
FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
//创建读取器,注意此处,如果用 new StreamReader(fs);会出现乱码
StreamReader sr = new StreamReader(fs,System.Text.Encoding.Default);
//读取文件
txtContent.Text = sr.ReadToEnd();
//关闭读取器
sr.Close();
//关闭文件流
fs.Close();
}
}
//写入按钮点击事件
private void btnWrite_Click(object sender, EventArgs e)
{
SaveFileDialog sfd=new SaveFileDialog();
sfd.Filter= "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
DialogResult dr=sfd.ShowDialog();
if(dr!=DialogResult.OK){return;}
FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
sw.Write(txtContent.Text);
sw.Close();
fs.Close();
}
}
}