将多个文件合并为一个文件 - 努力成长静待花开

时间:2024-03-08 21:58:26

实现效果:

  

知识运用:

  FileStream  和BinaryReader  及BinaryWriter类

 实现代码:

        /// <summary>
        /// 文件合并
        /// </summary>
        /// <param name="strFile">要合并的文件名称列表</param>
        /// <param name="strPath">合并后保存的文件路径</param>
        /// <param name="PBar">显示进度的进度条</param>
        public void CombinFile(string[] strFile,string strPath,ProgressBar PBar)
        {
            PBar.Maximum = strFile.Length;
            FileStream addStream = new FileStream(strPath,FileMode.Append);
            BinaryWriter addWriter = new BinaryWriter(addStream);
            FileStream tempStream = null;
            BinaryReader tempReader = null;
            for (int i = 0; i < strFile.Length; i++)
            {
                tempStream = new FileStream(strFile[i],FileMode.Open);
                tempReader = new BinaryReader(tempStream);
                addWriter.Write(tempReader.ReadBytes((int)tempStream.Length));
                tempReader.Close();
                tempStream.Close();
                PBar.Value = i + 1;
            }
            addWriter.Close();
            addStream.Close();
            MessageBox.Show("文件合并成功!");
        }