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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM