这个项目我用的是asp.net构建的,代码如下
1 PRotected void ByteToString_Click(object sender, EventArgs e) 2 { 3 4 5 string content = this.txtContent.Text.ToString(); 6 7 if (string.IsNullOrEmpty(content)) 8 { 9 return;10 }11 12 //string 转为byte数组13 byte[] array = Encoding.UTF8.GetBytes(content);14 15 //将byte数组转为string16 string result = Encoding.UTF8.GetString(array);17 18 19 Response.Write(result);20 21 22 }23 //利用byte[]数组写入文件24 protected void writerFile_Click(object sender, EventArgs e)25 {26 27 string content = this.txtContent.Text.ToString();28 29 if (string.IsNullOrEmpty(content))30 {31 return;32 }33 34 //将string转为byte数组35 byte[] array = Encoding.UTF8.GetBytes(content);36 37 string path = Server.MapPath("/test.txt");38 //创建一个文件流39 FileStream fs = new FileStream(path, FileMode.Create);40 41 //将byte数组写入文件中42 fs.Write(array, 0, array.Length);43 //所有流类型都要关闭流,否则会出现内存泄露问题44 fs.Close();45 46 Response.Write("保存文件成功");47 48 49 }50 //利用byte[]数组读取文件51 protected void readFile_Click(object sender, EventArgs e)52 {53 string path = Server.MapPath("/test.txt");54 55 FileStream fs = new FileStream(path, FileMode.Open);56 57 //获取文件大小58 long size = fs.Length;59 60 byte[] array = new byte[size];61 62 //将文件读到byte数组中63 fs.Read(array, 0, array.Length);64 65 fs.Close();66 67 //将byte数组转为string68 string result = Encoding.UTF8.GetString(array);69 70 71 Response.Write(result);72 73 74 75 }
新闻热点
疑难解答