C# 通过二进制,将多个文件合并为一个。
/// <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");
}