查看: 481|回复: 0

[ASP.NET教程] C# Byte[]数组读取和写入文件

发表于 2017-10-4 09:23:16
尚学堂AD
  1. <img src="http://img.it-home.org/data/attachment/forum/2017pic3/1216351-20170911112710407-857193854.png" alt=""><br>protected void ByteToString_Click(object sender, EventArgs e)
  2. {
  3. string content = this.txtContent.Text.ToString();
  4. if (string.IsNullOrEmpty(content))
  5. {
  6. return;
  7. }
  8. //string 转为byte数组
  9. byte[] array = Encoding.UTF8.GetBytes(content);
  10. //将byte数组转为string
  11. string result = Encoding.UTF8.GetString(array);
  12. Response.Write(result);
  13. }
  14. //利用byte[]数组写入文件
  15. protected void writerFile_Click(object sender, EventArgs e)
  16. {
  17. string content = this.txtContent.Text.ToString();
  18. if (string.IsNullOrEmpty(content))
  19. {
  20. return;
  21. }
  22. //将string转为byte数组
  23. byte[] array = Encoding.UTF8.GetBytes(content);
  24. string path = Server.MapPath("/test.txt");
  25. //创建一个文件流
  26. FileStream fs = new FileStream(path, FileMode.Create);
  27. //将byte数组写入文件中
  28. fs.Write(array, 0, array.Length);
  29. //所有流类型都要关闭流,否则会出现内存泄露问题
  30. fs.Close();
  31. Response.Write("保存文件成功");
  32. }
  33. //利用byte[]数组读取文件
  34. protected void readFile_Click(object sender, EventArgs e)
  35. {
  36. string path = Server.MapPath("/test.txt");
  37. FileStream fs = new FileStream(path, FileMode.Open);
  38. //获取文件大小
  39. long size = fs.Length;
  40. byte[] array = new byte[size];
  41. //将文件读到byte数组中
  42. fs.Read(array, 0, array.Length);
  43. fs.Close();
  44. //将byte数组转为string
  45. string result = Encoding.UTF8.GetString(array);
  46. Response.Write(result);
  47. }
复制代码



回复

使用道具 举报