您的位置:首页 > 编程语言 > C#

C#对文件操作小结

2008-05-28 14:05 597 查看
private void button2_Click(object sender, EventArgs e)
{
//创建一个二进制文件
BinaryWriter bw;
FileStream fs = new FileStream("D://mytest.data", FileMode.Create);
bw = new BinaryWriter(fs);
bw.Write("我的测试文章,123 ,welcome to you!");//写入
fs.Close();
bw.Close();//关闭

////读一个二进制文件
BinaryReader br;
string str = "";
FileStream fs2 = new FileStream("D://mytest.data", FileMode.Open);
br = new BinaryReader(fs2);
byte[] DocByte = br.ReadBytes((int)fs2.Length);

str = Encoding.UTF8.GetString(DocByte);
fs2.Close();
br.Close();

this.textBox1.Text = str;

}

private void button1_Click(object sender, EventArgs e)
{
//文本文件操作:创建/读取/拷贝/删除
string filepath = "D://myfile.txt";
StreamWriter sw = File.CreateText(filepath);
sw.Write("use write to write it");
sw.WriteLine("use sw writeline");
sw.Close();

StreamReader sr = File.OpenText(filepath);
string str = sr.ReadLine();
this.textBox1.Text = str;
sr.Close();
//文件的删除。
if (File.Exists(filepath))
{
File.Delete(filepath);
}

//流文件操作
FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//Byte[] info = new UTF8Encoding(true).GetBytes("This is my test file,也可用中文显示"); //转为bytes
//fs.Write(info, 0, info.Length);

//或者用StreamWriter
StreamWriter sw = new StreamWriter(fs);
sw.Write("This is my test file,也可用中文显示");
sw.Close();
fs.Close();

FileStream fs2 = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

byte[] cByte = new byte[1024];
fs2.Read(cByte, 0, cByte.Length);
string content = Encoding.UTF8.GetString(cByte);
this.textBox1.Text = content;
//或者用StreamReader来实现
StreamReader sr = new StreamReader(fs2);
//this.textBox1.Text = sr.ReadToEnd();

fs2.Close();
sr.Close();

}

附: //转换类型
System.Text.Encoding encode = System.Text.Encoding.Default;
byte[] bytes = encode.GetBytes("这是我的测试中文体");
string strout = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);
this.textBox1.Text = strout;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: