.Net实现合并文件的具体方法(2)


PackFileManager的LoadPackFile方法
       public void LoadPackFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }
            if (_pf != null)
            {
                _pf.Close();
                _pf = null;
            }
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            if (br.ReadString() != "PackFile")
            {
                throw new InvalidCoalescentFileException("该文件不是有效的包文件");
            }
            this._pf = new PackFile(fs,br);
        }


此时,我们在生成时写入的字符串"PackFile" 就有了明确的功能
PackFile的构造函数

复制代码 代码如下:


        internal PackFile(FileStream srcFile,BinaryReader br)
            {
                this._sourceFile = srcFile;
                _br = br;
                this._fileCount = _br.ReadInt32();//取文件数
                for (int i = 1; i <= _fileCount; i++)
                {
                    this._fileLengthList.Add(_br.ReadInt64());
                }
                for (int i = 1; i <= _fileCount; i++)
                {
                    this._shortNameList.Add(_br.ReadString());
                }
                this._contentStartPos = _sourceFile.Position;//设置实体文件总起始位置
            }
 


PackFile.GetBytes()

复制代码 代码如下:


            public byte[] GetBytes(int index)
            {
                long startPos = this._contentStartPos;
                for (int i = 0; i < index; i++)
                {
                    startPos += this._fileLengthList[i];
                }
                _sourceFile.Position = startPos; //设置某文件内容的起始位置
                return _br.ReadBytes((int)_fileLengthList[index]);
            }


这只是一个草案,我们还可以加入压缩、或是像ZIP文件那样的嵌套文件夹功能,改进后的代码别忘与我分享哦。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgdwj.html