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


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); }

转载于:https://www.cnblogs.com/ldyblogs/p/Byte.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值