码迷,mamicode.com
首页 > 编程语言 > 详细

C# Byte[]数组读取和写入文件

时间:2017-09-11 12:18:08      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:writer   数组   文件中   return   log   path   tco   oid   object   

技术分享
protected
void ByteToString_Click(object sender, EventArgs e) { string content = this.txtContent.Text.ToString(); if (string.IsNullOrEmpty(content)) { return; } //string 转为byte数组 byte[] array = Encoding.UTF8.GetBytes(content); //将byte数组转为string string result = Encoding.UTF8.GetString(array); Response.Write(result); } //利用byte[]数组写入文件 protected void writerFile_Click(object sender, EventArgs e) { string content = this.txtContent.Text.ToString(); if (string.IsNullOrEmpty(content)) { return; } //将string转为byte数组 byte[] array = Encoding.UTF8.GetBytes(content); string path = Server.MapPath("/test.txt"); //创建一个文件流 FileStream fs = new FileStream(path, FileMode.Create); //将byte数组写入文件中 fs.Write(array, 0, array.Length); //所有流类型都要关闭流,否则会出现内存泄露问题 fs.Close(); Response.Write("保存文件成功"); } //利用byte[]数组读取文件 protected void readFile_Click(object sender, EventArgs e) { string path = Server.MapPath("/test.txt"); FileStream fs = new FileStream(path, FileMode.Open); //获取文件大小 long size = fs.Length; byte[] array = new byte[size]; //将文件读到byte数组中 fs.Read(array, 0, array.Length); fs.Close(); //将byte数组转为string string result = Encoding.UTF8.GetString(array); Response.Write(result); }

技术分享

C# Byte[]数组读取和写入文件

标签:writer   数组   文件中   return   log   path   tco   oid   object   

原文地址:http://www.cnblogs.com/ldyblogs/p/Byte.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!