protected void ByteToString_Click(object sender, EventArgs e) { string content = this.txtContent.Text.ToString(); if (string.IsNullOrEmpty(content)) { ...
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); }