這個項目我用的是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數組轉為string
16 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數組轉為string
68 string result = Encoding.UTF8.GetString(array);
69
70
71 Response.Write(result);
72
73
74
75 }