C# 經過二進制,將多個文件合併爲一個。java
/// <summary> /// 合併文件 /// </summary> /// <param name="strDirectory"></param> /// <param name="strMergeResultFile"></param> private void MergeFiles(string strInputDirectory, string strMergeResultFile) { string[] arrFileNames = Directory.GetFiles(strInputDirectory); int iSumFile = arrFileNames.Length; //progressBar1.Maximum = iSumFile; FileStream AddStream = new FileStream(strMergeResultFile + "_temp", FileMode.OpenOrCreate); BinaryWriter AddWriter = new BinaryWriter(AddStream); long firstFileLength = 0; FileStream TempStream = null; BinaryReader TempReader = null; //文件長度列表 string allFileLength = ""; //文件長度和文件內容疊加 { for (int i = 0; i < iSumFile; i++) { TempStream = new FileStream(arrFileNames[i], FileMode.Open); TempReader = new BinaryReader(TempStream); AddWriter.Write(TempReader.ReadBytes((int)TempStream.Length)); if (firstFileLength == 0) { firstFileLength = TempReader.BaseStream.Length; allFileLength = firstFileLength.ToString().PadLeft(20, '0'); } //暫時只處理2個文件的狀況,下面是多文件 //allFileLength += "," + TempReader.BaseStream.Length.ToString().PadLeft(20, '0'); TempReader.Close(); TempStream.Close(); } allFileLength = allFileLength.Trim(','); //釋放資源 AddWriter.Flush(); AddWriter.Close(); AddStream.Close(); TempStream = null; TempReader = null; } //建立含有頭信息的文件- 也達到了加密的效果 { System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); byte[] BytesMessage = UTF8.GetBytes(allFileLength); AddStream = new FileStream(strMergeResultFile + "_r", FileMode.OpenOrCreate); AddWriter = new BinaryWriter(AddStream); //文件頭 AddWriter.Write(BytesMessage); //寫入原來文件 TempStream = new FileStream(strMergeResultFile, FileMode.Open); TempReader = new BinaryReader(TempStream); AddWriter.Write(TempReader.ReadBytes((int)TempStream.Length)); long cc = TempReader.BaseStream.Length; TempReader.Close(); AddWriter.Flush(); AddWriter.Close(); TempStream.Close(); //釋放 TempReader = null; AddWriter = null; TempStream = null; } //刪掉臨時 File.Delete(strMergeResultFile + "_temp"); }