byte[]讀取與寫入
阿新 • • 發佈:2018-11-01
FileStream fs1 = new FileStream(@"E:\tenp\doc\111.txt", FileMode.Open, FileAccess.Read, FileShare.Read); FileStream fs2 = new FileStream(@"E:\temp\doc\222.txt", FileMode.Create, FileAccess.Write, FileShare.None); byte []farr = new byte[1024]; const int rbuffer=1024; //fs1.ReadByte(); //讀取單個位元組,返回-1表示讀完 while (fs1.Read(farr, 0, rbuffer)!=0) //返回0表示讀完 { fs2.Write(farr, 0, rbuffer); } fs1.Close(); fs2.Close();
讀取與寫入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); }