private static int GetFileHashImpl(FileInfo file)
        {
            if (!file.Exists)
            {
                return(-1);
            }

            if (SB3UGS_Utils.FileIsAssetBundle(file))
            {
                try
                {
                    return(SB3UGS_Utils.HashFileContents(file.FullName));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to get content hash with SB3UGS, falling back to full hash. File: " + file.FullName + " Exception: " + ex.Message);
                }
            }

            if (_crc == null)
            {
                _crc = new CRC32();
            }
            else
            {
                _crc.Reset();
            }

            using (var rs = file.OpenRead())
            {
                return(_crc.GetCrc32(rs));
            }
        }
 /// <summary>
 /// Gets the CRC of file.
 /// </summary>
 /// <param name="psFile">The file path.</param>
 /// <returns>System.Int64.</returns>
 public static long GetCrcFile(string psFile)
 {
     using (var streamFile = new FileStream(psFile, FileMode.Open))
     {
         var crcFile = new CRC32();
         return(crcFile.GetCrc32(streamFile));
     }
 }
Esempio n. 3
0
        public void SimpleCRC32Test()
        {
            string mockObj = @"SABNFGTREJ32435457#@$^%&&([p]\[]::<>?<ASCZXNOLółźćżą111"; // crc32=2259372540
            CRC32  crc     = new CRC32();
            Stream str     = new MemoryStream(sHGG.StrToByteArray(mockObj));
            uint   crc32   = crc.GetCrc32(str);

            Assert.IsNotNull(crc32);
            Assert.AreEqual(crc32, 2259372540);
        }
Esempio n. 4
0
        private void importPatchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.Title           = "Please select a compressed patch file";
            openFileDialog.CheckFileExists = false;
            openFileDialog.Filter          = "Zip File (*.zip)|*.zip|Rar File (*.rar)|*.rar";

            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                if (!File.Exists(openFileDialog.FileName))
                {
                    MessageBox.Show(this, "That file does not exist!");
                    return;
                }

                CRC32 crc32 = new CRC32();
                crc32.PercentCompleteChange += new ProgressChangeHandler(OnPercentChange);
                FileStream stream = File.OpenRead(openFileDialog.FileName);
                uint       crc    = crc32.GetCrc32(stream);
                stream.Close();

                string        location = string.Empty;
                PathInputForm form     = new PathInputForm();
                form.PatchLocation = "http://";

                if (form.ShowDialog(this) == DialogResult.Cancel)
                {
                    return;
                }

                if (!form.PatchLocation.Contains(Path.GetFileName(openFileDialog.FileName)))
                {
                    if (!form.PatchLocation.EndsWith("/"))
                    {
                        form.PatchLocation += "/";
                    }

                    form.PatchLocation += Path.GetFileName(openFileDialog.FileName);
                }

                PatchlistFile file = new PatchlistFile(form.PatchLocation, crc, new FileInfo(openFileDialog.FileName).Length);

                if (!listBox.Items.Contains(file) && !DuplicateFileNames(file))
                {
                    _needsSaving = true;
                    listBox.Items.Add(file);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Get the CRC32 checksum of the input stream.
        /// </summary>
        /// <param name="stream">File Stream for which to generate the checksum.</param>
        /// <returns>String containing the hexidecimal representation of the CRC32 of the input stream.</returns>
        public static string GetCrc32OfFullFile(FileStream stream)
        {
            // get incoming stream position
            long initialStreamPosition = stream.Position;

            // move to zero position
            stream.Seek(0, SeekOrigin.Begin);

            // calculate CRC32
            CRC32 crc32 = new CRC32();
            int   ret   = crc32.GetCrc32(stream);

            // return stream to incoming position
            stream.Position = initialStreamPosition;

            return(ret.ToString("X8", CultureInfo.InvariantCulture));
        }
Esempio n. 6
0
        /**
         * Returns the "public" hash of the email address, i.e., the one we give out
         * to select partners via our API.
         *
         * @param  string _email An email address to hash
         * @return string        A public hash of the form crc32(_email)_md5(_email)
         */
        public static string email_get_public_hash(string email)
        {
            if (!string.IsNullOrEmpty(email))
            {
                email = email.ToLower().Trim();
                byte[] rawBytes = System.Text.UTF8Encoding.UTF8.GetBytes(email);

                CRC32  crc       = new CRC32();
                UInt32 crcResult = crc.GetCrc32(new System.IO.MemoryStream(rawBytes));

                MD5    md5       = new MD5CryptoServiceProvider();
                byte[] md5Result = md5.ComputeHash(rawBytes);
                string md5Data   = ToHexString(md5Result).ToLower();

                return(crcResult.ToString() + "_" + md5Data);
            }
            return("");
        }
Esempio n. 7
0
        private void importPatchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.Title = "Please select a compressed patch file";
            openFileDialog.CheckFileExists = false;
            openFileDialog.Filter = "Zip File (*.zip)|*.zip|Rar File (*.rar)|*.rar";

            if( openFileDialog.ShowDialog(this) == DialogResult.OK )
            {
                if( !File.Exists(openFileDialog.FileName) )
                {
                    MessageBox.Show(this, "That file does not exist!");
                    return;
                }

                CRC32 crc32 = new CRC32();
                crc32.PercentCompleteChange += new ProgressChangeHandler(OnPercentChange);
                FileStream stream = File.OpenRead(openFileDialog.FileName);
                uint crc = crc32.GetCrc32(stream);
                stream.Close();

                string location = string.Empty;
                PathInputForm form = new PathInputForm();
                form.PatchLocation = "http://";

                if( form.ShowDialog(this) == DialogResult.Cancel )
                    return;

                if (!form.PatchLocation.Contains(Path.GetFileName(openFileDialog.FileName)))
                {
                    if (!form.PatchLocation.EndsWith("/"))
                        form.PatchLocation += "/";

                    form.PatchLocation += Path.GetFileName(openFileDialog.FileName);
                }

                PatchlistFile file = new PatchlistFile(form.PatchLocation, crc, new FileInfo(openFileDialog.FileName).Length);

                if (!listBox.Items.Contains(file) && !DuplicateFileNames(file))
                {
                    _needsSaving = true;
                    listBox.Items.Add(file);
                }
            }
        }
Esempio n. 8
0
        // These two data types are supported in DotNetZip, but only if .NET Framework is targeted.
        //private SelfExtractorFlavor _selfExtractorFlavor;
        //private SelfExtractorSaveOptions _selfExtractorSaveOptions;

        public void CallAll()
        {
            // These two apis are supported in DotNetZip, but only if .NET Framework is targeted.
            //_zipFile.SaveSelfExtractor(_string, _selfExtractorFlavor);
            //_zipFile.SaveSelfExtractor(_string, _selfExtractorSaveOptions);

            //Project: Ionic.Zip
            _bZip2InputStream.Close();
            _bZip2InputStream.Flush();
            _int  = _bZip2InputStream.Read(_bytes, _int, _int);
            _int  = _bZip2InputStream.ReadByte();
            _long = _bZip2InputStream.Seek(_long, _seekOrigin);
            _bZip2InputStream.SetLength(_long);
            _bZip2InputStream.Write(_bytes, _int, _int);
            _bZip2OutputStream.Close();
            _bZip2OutputStream.Flush();
            _int  = _bZip2OutputStream.Read(_bytes, _int, _int);
            _long = _bZip2OutputStream.Seek(_long, _seekOrigin);
            _bZip2OutputStream.SetLength(_long);
            _bZip2OutputStream.Write(_bytes, _int, _int);
            _parallelBZip2OutputStream.Close();
            _parallelBZip2OutputStream.Flush();
            _int  = _parallelBZip2OutputStream.Read(_bytes, _int, _int);
            _long = _parallelBZip2OutputStream.Seek(_long, _seekOrigin);
            _parallelBZip2OutputStream.SetLength(_long);
            _parallelBZip2OutputStream.Write(_bytes, _int, _int);
            _crc32.Combine(_int, _int);
            _int = _crc32.ComputeCrc32(_int, _byte);
            _int = _crc32.GetCrc32(_stream);
            _int = _crc32.GetCrc32AndCopy(_stream, _stream);
            _crc32.Reset();
            _crc32.SlurpBlock(_bytes, _int, _int);
            _crc32.UpdateCRC(_byte);
            _crc32.UpdateCRC(_byte, _int);
            _crcCalculatorStream.Close();
            _crcCalculatorStream.Flush();
            _int  = _crcCalculatorStream.Read(_bytes, _int, _int);
            _long = _crcCalculatorStream.Seek(_long, _seekOrigin);
            _crcCalculatorStream.SetLength(_long);
            _crcCalculatorStream.Write(_bytes, _int, _int);
            _zipEntriesCollection = _fileSelector.SelectEntries(_zipFile);
            _zipEntriesCollection = _fileSelector.SelectEntries(_zipFile, _string);
            _stringsCollection    = _fileSelector.SelectFiles(_string);
            _stringsReadOnly      = _fileSelector.SelectFiles(_string, _bool);
            _string = _fileSelector.ToString();
            _bool   = _comHelper.CheckZip(_string);
            _bool   = _comHelper.CheckZipPassword(_string, _string);
            _comHelper.FixZipDirectory(_string);
            _string = _comHelper.GetZipLibraryVersion();
            _bool   = _comHelper.IsZipFile(_string);
            _bool   = _comHelper.IsZipFileWithExtract(_string);
            _countingStream.Adjust(_long);
            _countingStream.Flush();
            _int  = _countingStream.Read(_bytes, _int, _int);
            _long = _countingStream.Seek(_long, _seekOrigin);
            _countingStream.SetLength(_long);
            _countingStream.Write(_bytes, _int, _int);
            _zipEntry.Extract();
            _zipEntry.Extract(_extractExistingFileAction);
            _zipEntry.Extract(_string);
            _zipEntry.Extract(_string, _extractExistingFileAction);
            _zipEntry.Extract(_stream);
            _zipEntry.ExtractWithPassword(_extractExistingFileAction, _string);
            _zipEntry.ExtractWithPassword(_string);
            _zipEntry.ExtractWithPassword(_string, _extractExistingFileAction, _string);
            _zipEntry.ExtractWithPassword(_string, _string);
            _zipEntry.ExtractWithPassword(_stream, _string);
            _crcCalculatorStream = _zipEntry.OpenReader();
            _crcCalculatorStream = _zipEntry.OpenReader(_string);
            _zipEntry.SetEntryTimes(_datetime, _datetime, _datetime);
            _string   = _zipEntry.ToString();
            _zipEntry = _zipFile.AddDirectory(_string);
            _zipEntry = _zipFile.AddDirectory(_string, _string);
            _zipEntry = _zipFile.AddDirectoryByName(_string);
            _zipEntry = _zipFile.AddEntry(_string, _bytes);
            _zipEntry = _zipFile.AddEntry(_string, _openDelegate, _closeDelegate);
            _zipEntry = _zipFile.AddEntry(_string, _writeDelegate);
            _zipEntry = _zipFile.AddEntry(_string, _string);
            _zipEntry = _zipFile.AddEntry(_string, _string, _encoding);
            _zipEntry = _zipFile.AddEntry(_string, _stream);
            _zipEntry = _zipFile.AddFile(_string);
            _zipEntry = _zipFile.AddFile(_string, _string);
            _zipFile.AddFiles(_strings);
            _zipFile.AddFiles(_strings, _bool, _string);
            _zipFile.AddFiles(_strings, _string);
            _zipEntry = _zipFile.AddItem(_string);
            _zipEntry = _zipFile.AddItem(_string, _string);
            _zipFile.AddSelectedFiles(_string);
            _zipFile.AddSelectedFiles(_string, _bool);
            _zipFile.AddSelectedFiles(_string, _string);
            _zipFile.AddSelectedFiles(_string, _string, _bool);
            _zipFile.AddSelectedFiles(_string, _string, _string);
            _zipFile.AddSelectedFiles(_string, _string, _string, _bool);
            _bool = _zipFile.ContainsEntry(_string);
            _zipFile.Dispose();
            _zipFile.ExtractAll(_string);
            _zipFile.ExtractAll(_string, _extractExistingFileAction);
            _zipFile.ExtractSelectedEntries(_string);
            _zipFile.ExtractSelectedEntries(_string, _extractExistingFileAction);
            _zipFile.ExtractSelectedEntries(_string, _string);
            _zipFile.ExtractSelectedEntries(_string, _string, _string);
            _zipFile.ExtractSelectedEntries(_string, _string, _string, _extractExistingFileAction);
            _enumerator = _zipFile.GetNewEnum();
            _zipFile.Initialize(_string);
            _zipFile.RemoveEntries(_zipEntriesCollection);
            _zipFile.RemoveEntries(_stringsCollection);
            _zipFile.RemoveEntry(_zipEntry);
            _zipFile.RemoveEntry(_string);
            _int = _zipFile.RemoveSelectedEntries(_string);
            _int = _zipFile.RemoveSelectedEntries(_string, _string);
            _zipFile.Save();
            _zipFile.Save(_string);
            _zipFile.Save(_stream);
            _zipEntriesCollection = _zipFile.SelectEntries(_string);
            _zipEntriesCollection = _zipFile.SelectEntries(_string, _string);
            _string   = _zipFile.ToString();
            _zipEntry = _zipFile.UpdateDirectory(_string);
            _zipEntry = _zipFile.UpdateDirectory(_string, _string);
            _zipEntry = _zipFile.UpdateEntry(_string, _bytes);
            _zipEntry = _zipFile.UpdateEntry(_string, _openDelegate, _closeDelegate);
            _zipEntry = _zipFile.UpdateEntry(_string, _writeDelegate);
            _zipEntry = _zipFile.UpdateEntry(_string, _string);
            _zipEntry = _zipFile.UpdateEntry(_string, _string, _encoding);
            _zipEntry = _zipFile.UpdateEntry(_string, _stream);
            _zipEntry = _zipFile.UpdateFile(_string);
            _zipFile.UpdateFile(_string, _string);
            _zipFile.UpdateFiles(_strings);
            _zipFile.UpdateFiles(_strings, _string);
            _zipFile.UpdateItem(_string);
            _zipFile.UpdateItem(_string, _string);
            _zipFile.UpdateSelectedFiles(_string, _string, _string, _bool);
            _zipInputStream.Flush();
            _zipEntry = _zipInputStream.GetNextEntry();
            _int      = _zipInputStream.Read(_bytes, _int, _int);
            _long     = _zipInputStream.Seek(_long, _seekOrigin);
            _zipInputStream.SetLength(_long);
            _string = _zipInputStream.ToString();
            _zipInputStream.Write(_bytes, _int, _int);
            _bool = _zipOutputStream.ContainsEntry(_string);
            _zipOutputStream.Flush();
            _zipEntry = _zipOutputStream.PutNextEntry(_string);
            _int      = _zipOutputStream.Read(_bytes, _int, _int);
            _long     = _zipOutputStream.Seek(_long, _seekOrigin);
            _zipOutputStream.SetLength(_long);
            _string = _zipOutputStream.ToString();
            _zipOutputStream.Write(_bytes, _int, _int);
            _deflateStream.Flush();
            _int  = _deflateStream.Read(_bytes, _int, _int);
            _long = _deflateStream.Seek(_long, _seekOrigin);
            _deflateStream.SetLength(_long);
            _deflateStream.Write(_bytes, _int, _int);
            _gZipStream.Flush();
            _int  = _gZipStream.Read(_bytes, _int, _int);
            _long = _gZipStream.Seek(_long, _seekOrigin);
            _gZipStream.SetLength(_long);
            _gZipStream.Write(_bytes, _int, _int);
            _parallelDeflateOutputStream.Close();
            _parallelDeflateOutputStream.Flush();
            _int = _parallelDeflateOutputStream.Read(_bytes, _int, _int);
            _parallelDeflateOutputStream.Reset(_stream);
            _long = _parallelDeflateOutputStream.Seek(_long, _seekOrigin);
            _parallelDeflateOutputStream.SetLength(_long);
            _parallelDeflateOutputStream.Write(_bytes, _int, _int);

            // Static
            _bool = ZipFile.CheckZip(_string);
            _bool = ZipFile.CheckZip(_string, _bool, _textWriter);
            _bool = ZipFile.CheckZipPassword(_string, _string);
            ZipFile.FixZipDirectory(_string);
            _bool    = ZipFile.IsZipFile(_string);
            _bool    = ZipFile.IsZipFile(_string, _bool);
            _bool    = ZipFile.IsZipFile(_stream, _bool);
            _zipFile = ZipFile.Read(_string);
            _zipFile = ZipFile.Read(_string, _readOptions);
            _zipFile = ZipFile.Read(_stream);
            _zipFile = ZipFile.Read(_stream, _readOptions);
            _uint    = Adler.Adler32(_uint, _bytes, _int, _int);
            _bytes   = DeflateStream.CompressBuffer(_bytes);
            _bytes   = DeflateStream.CompressString(_string);
            _bytes   = DeflateStream.UncompressBuffer(_bytes);
            _string  = DeflateStream.UncompressString(_bytes);
            _bytes   = GZipStream.CompressBuffer(_bytes);
            _bytes   = GZipStream.CompressString(_string);
            _bytes   = GZipStream.UncompressBuffer(_bytes);
            _string  = GZipStream.UncompressString(_bytes);
            _bytes   = ZlibStream.CompressBuffer(_bytes);
            _bytes   = ZlibStream.CompressString(_string);
            _bytes   = ZlibStream.UncompressBuffer(_bytes);
            _string  = ZlibStream.UncompressString(_bytes);
        }
Esempio n. 9
0
        public static void SerializeDirToPak(string dir, string pakfile)
        {
            string[] allFiles = recursiveGetFiles(dir, "");

            List <Dir> dirEntryList = new List <Dir>();

            using (FormattedWriter fw = new FormattedWriter(pakfile)) {
                // Write files
                foreach (var file in allFiles)
                {
                    fw.Write(new Signature()
                    {
                        signature = stringFileHeader2
                    });
                    File   f          = new File();
                    byte[] bytes      = System.IO.File.ReadAllBytes(Path.Combine(dir, file));
                    byte[] compressed = decryptBytesWithTable(ZlibCodecCompress(bytes), 0x3ff, 1, table2);
                    f.compressedSize    = (uint)compressed.Length;
                    f.compressionMethod = 8;
                    CRC32 dataCheckSum = new CRC32();
                    f.crc                    = dataCheckSum.GetCrc32(new MemoryStream(bytes));
                    f.data                   = compressed;
                    f.extractSystem          = 0;
                    f.extractVersion         = 20;
                    f.extraField             = new byte[0];
                    f.extraFieldLength       = 0;
                    f.filename               = Encoding.UTF8.GetBytes(file);
                    f.filenameLength         = (ushort)f.filename.Length;
                    f.generalPurposeFlagBits = 0;
                    f.lastModDate            = 0;
                    f.lastModTime            = 0;
                    f.uncompressedSize       = (uint)bytes.Length;
                    fw.Write(f);

                    Dir d = new Dir();
                    d.comment                = new byte[0];
                    d.commentLength          = 0;
                    d.compressedSize         = f.compressedSize;
                    d.compressType           = f.compressionMethod;
                    d.crc                    = f.crc;
                    d.createSystem           = f.extractSystem;
                    d.createVersion          = f.extractVersion;
                    d.date                   = f.lastModDate;
                    d.diskNumberStart        = 0;
                    d.externalFileAttributes = 33;
                    d.extractSystem          = f.extractSystem;
                    d.extractVersion         = f.extractVersion;
                    d.extraField             = new byte[0];
                    d.extraFieldLength       = 0;
                    d.filename               = f.filename;
                    d.filenameLength         = f.filenameLength;
                    d.flagBits               = f.generalPurposeFlagBits;
                    d.internalFileAttributes = 0;
                    d.localHeaderOffset      = 0;
                    d.time                   = f.lastModTime;
                    d.uncompressedSize       = f.uncompressedSize;

                    dirEntryList.Add(d);
                }

                var dirEntryListStartPos = fw.BaseStream.BaseStream.Position;
                foreach (var d in dirEntryList)
                {
                    fw.Write(new Signature()
                    {
                        signature = stringCentralDir2
                    });
                    fw.Write(d);
                }
                var dirEntryListEndPos = fw.BaseStream.BaseStream.Position;

                End e = new End();
                e.byteSizeOfCentralDirectory = (uint)(dirEntryListEndPos - dirEntryListStartPos);
                e.centralDirRecordsOnDisk    = (short)dirEntryList.Count;
                e.centralDirStartDisk        = 0;
                e.comment       = new byte[0];
                e.commentLength = 0;
                e.diskNumber    = 0;
                e.offsetOfStartOfCentralDirectory = (uint)dirEntryListStartPos;
                e.totalNumOfCentralDirRecords     = (short)dirEntryList.Count;

                fw.Write(new Signature()
                {
                    signature = stringEndArchive2
                });
                fw.Write(e);
            }
        }
Esempio n. 10
0
        int detectVersion(byte[] data, uint uncompressedSize, int crc, ushort compressionMethod)
        {
            if (compressionMethod != 0 && compressionMethod != 8)
            {
                throw new Exception("Unknown compression method " + compressionMethod + "!");
            }

            // version 2
            if (compressionMethod == 8)
            {
                try {
                    var   bytes        = ZlibCodecDecompress(decryptBytesWithTable(data, 0x3ff, 1, table2));
                    CRC32 dataCheckSum = new CRC32();
                    int   checkSum     = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                    if (bytes.Length == uncompressedSize && checkSum == crc)
                    {
                        return(2);
                    }
                } catch { }
            }
            else
            {
                var   bytes        = decryptBytesWithTable(data, 0x3ff, 1, table2);
                CRC32 dataCheckSum = new CRC32();
                int   checkSum     = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                if (bytes.Length == uncompressedSize && checkSum == crc)
                {
                    return(2);
                }
            }

            //version 1
            if (compressionMethod == 8)
            {
                try {
                    var bytes = ZlibCodecDecompress(decryptBytesWithTable(data, 0x1f, 32, table1));

                    CRC32 dataCheckSum = new CRC32();
                    int   checkSum     = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                    if (bytes.Length == uncompressedSize && checkSum == crc)
                    {
                        return(1);
                    }
                } catch { }
            }
            else
            {
                var   bytes        = decryptBytesWithTable(data, 0x1f, 32, table1);
                CRC32 dataCheckSum = new CRC32();
                int   checkSum     = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                if (bytes.Length == uncompressedSize && checkSum == crc)
                {
                    return(2);
                }
            }


            return(0);
        }
Esempio n. 11
0
        int detectVersion(byte[] data, uint uncompressedSize, int crc, ushort compressionMethod)
        {
            if (compressionMethod != 0 && compressionMethod != 8) {
                throw new Exception("Unknown compression method " + compressionMethod + "!");
            }

            // version 2
            if (compressionMethod == 8) {
                try {
                    var bytes = ZlibCodecDecompress(decryptBytesWithTable(data, 0x3ff, 1, table2));
                    CRC32 dataCheckSum = new CRC32();
                    int checkSum = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                    if (bytes.Length == uncompressedSize && checkSum == crc) {
                        return 2;
                    }
                } catch { }

            } else {
                var bytes = decryptBytesWithTable(data, 0x3ff, 1, table2);
                CRC32 dataCheckSum = new CRC32();
                int checkSum = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                if (bytes.Length == uncompressedSize && checkSum == crc) {
                    return 2;
                }
            }

            //version 1
            if (compressionMethod == 8) {
                try {
                    var bytes = ZlibCodecDecompress(decryptBytesWithTable(data, 0x1f, 32, table1));

                    CRC32 dataCheckSum = new CRC32();
                    int checkSum = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                    if (bytes.Length == uncompressedSize && checkSum == crc) {
                        return 1;
                    }
                } catch { }

            } else {
                var bytes = decryptBytesWithTable(data, 0x1f, 32, table1);
                CRC32 dataCheckSum = new CRC32();
                int checkSum = dataCheckSum.GetCrc32(new MemoryStream(bytes));

                if (bytes.Length == uncompressedSize && checkSum == crc) {
                    return 2;
                }
            }

            return 0;
        }
Esempio n. 12
0
        public static void SerializeDirToPak(string dir, string pakfile)
        {
            string[] allFiles = recursiveGetFiles(dir, "");

            List<Dir> dirEntryList = new List<Dir>();

            using (FormattedWriter fw = new FormattedWriter(pakfile)) {
                // Write files
                foreach (var file in allFiles) {
                    fw.Write(new Signature() { signature = stringFileHeader2 });
                    File f = new File();
                    byte[] bytes = System.IO.File.ReadAllBytes(Path.Combine(dir, file));
                    byte[] compressed = decryptBytesWithTable(ZlibCodecCompress(bytes), 0x3ff, 1, table2);
                    f.compressedSize = (uint)compressed.Length;
                    f.compressionMethod = 8;
                    CRC32 dataCheckSum = new CRC32();
                    f.crc = dataCheckSum.GetCrc32(new MemoryStream(bytes));
                    f.data = compressed;
                    f.extractSystem = 0;
                    f.extractVersion = 20;
                    f.extraField = new byte[0];
                    f.extraFieldLength = 0;
                    f.filename = Encoding.UTF8.GetBytes(file);
                    f.filenameLength = (ushort)f.filename.Length;
                    f.generalPurposeFlagBits = 0;
                    f.lastModDate = 0;
                    f.lastModTime = 0;
                    f.uncompressedSize = (uint)bytes.Length;
                    fw.Write(f);

                    Dir d = new Dir();
                    d.comment = new byte[0];
                    d.commentLength = 0;
                    d.compressedSize = f.compressedSize;
                    d.compressType = f.compressionMethod;
                    d.crc = f.crc;
                    d.createSystem = f.extractSystem;
                    d.createVersion = f.extractVersion;
                    d.date = f.lastModDate;
                    d.diskNumberStart = 0;
                    d.externalFileAttributes = 33;
                    d.extractSystem = f.extractSystem;
                    d.extractVersion = f.extractVersion;
                    d.extraField = new byte[0];
                    d.extraFieldLength = 0;
                    d.filename = f.filename;
                    d.filenameLength = f.filenameLength;
                    d.flagBits = f.generalPurposeFlagBits;
                    d.internalFileAttributes = 0;
                    d.localHeaderOffset = 0;
                    d.time = f.lastModTime;
                    d.uncompressedSize = f.uncompressedSize;

                    dirEntryList.Add(d);
                }

                var dirEntryListStartPos = fw.BaseStream.BaseStream.Position;
                foreach (var d in dirEntryList) {
                    fw.Write(new Signature() { signature = stringCentralDir2 });
                    fw.Write(d);
                }
                var dirEntryListEndPos = fw.BaseStream.BaseStream.Position;

                End e = new End();
                e.byteSizeOfCentralDirectory = (uint)(dirEntryListEndPos - dirEntryListStartPos);
                e.centralDirRecordsOnDisk = (short)dirEntryList.Count;
                e.centralDirStartDisk = 0;
                e.comment = new byte[0];
                e.commentLength = 0;
                e.diskNumber = 0;
                e.offsetOfStartOfCentralDirectory = (uint)dirEntryListStartPos;
                e.totalNumOfCentralDirRecords = (short)dirEntryList.Count;

                fw.Write(new Signature() { signature = stringEndArchive2 });
                fw.Write(e);
            }
        }
Esempio n. 13
0
        static void WriteData(Dictionary <string, string> resPathDic)
        {
            AssetBundleConfig config = new AssetBundleConfig();

            config.ABList = new List <ABBase>();
            foreach (string path in resPathDic.Keys)
            {
                if (!ValidPath(path))
                {
                    continue;
                }

                ABBase abBase = new ABBase();
                abBase.Path       = path;
                abBase.Crc        = CRC32.GetCrc32(path);
                abBase.ABName     = resPathDic[path];
                abBase.AssetName  = path.Remove(0, path.LastIndexOf("/") + 1);
                abBase.ABDependce = new List <string>();
                string[] resDependce = AssetDatabase.GetDependencies(path);
                for (int i = 0; i < resDependce.Length; i++)
                {
                    string tempPath = resDependce[i];
                    if (tempPath == path || path.EndsWith(".cs"))
                    {
                        continue;
                    }

                    string abName = "";
                    if (resPathDic.TryGetValue(tempPath, out abName))
                    {
                        if (abName == resPathDic[path])
                        {
                            continue;
                        }

                        if (!abBase.ABDependce.Contains(abName))
                        {
                            abBase.ABDependce.Add(abName);
                        }
                    }
                }
                config.ABList.Add(abBase);
            }

            //写入xml
            string xmlPath = Application.dataPath + "/AssetBundleConfig.xml";

            if (File.Exists(xmlPath))
            {
                File.Delete(xmlPath);
            }

            FileStream    fileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            StreamWriter  sw         = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
            XmlSerializer xs         = new XmlSerializer(config.GetType());

            xs.Serialize(sw, config);
            sw.Close();
            fileStream.Close();

            //写入二进制
            foreach (ABBase abBase in config.ABList)
            {
                abBase.Path = "";
            }
            FileStream fs = new FileStream(ABBYTEPATH, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

            fs.Seek(0, SeekOrigin.Begin);
            fs.SetLength(0);
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fs, config);
            fs.Close();
            AssetDatabase.Refresh();
            SetABName("AssetBundleConfig", ABBYTEPATH);
        }