private void WriteData(Stream stream)
        {
            if (_originalStream != null)
            {
                WriteOriginalData(stream);
                return;
            }
            bool closeFileStream = false;

            if (_fileStream == null)
            {
                _fileStream     = File.OpenRead(_fileName);
                closeFileStream = true;
            }
            long startPosition = stream.Position;

            _uncompressedSize = 0;
            _compressedSize   = 0;
            _crc32            = Crc32Hash.DefaultSeed;
            Stream outStream = stream;

            if (CompressionMethod == (uint)CompressionType.Deflate)
            {
                outStream = new DeflateStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression, true);
            }

            int bytesRead;
            var buffer = new byte[WriteBufferSize];

            do
            {
                bytesRead = _fileStream.Read(buffer, 0, WriteBufferSize);
                if (bytesRead <= 0)
                {
                    break;
                }
                _uncompressedSize += (uint)bytesRead;
                outStream.Write(buffer, 0, bytesRead);
                _crc32 = Crc32Hash.CalculateHash(_crc32, buffer, bytesRead);
            } while (bytesRead == WriteBufferSize);
            _crc32 ^= Crc32Hash.DefaultSeed;
            outStream.Flush();

            if (CompressionMethod == (uint)CompressionType.Deflate)
            {
                outStream.Close();
            }
            _compressedSize = (uint)(stream.Position - startPosition);
            if (closeFileStream)
            {
                _fileStream.Close();
                _fileStream = null;
            }
        }
Esempio n. 2
0
        public static uint CalculateHash(string fileSystemPath)
        {
            uint crc32 = Crc32Hash.DefaultSeed;

            using (var stream = File.OpenRead(fileSystemPath))
            {
                int bytesRead;
                var buffer = new byte[BufferSize];
                do
                {
                    bytesRead = stream.Read(buffer, 0, BufferSize);
                    if (bytesRead <= 0)
                    {
                        break;
                    }
                    crc32 = Crc32Hash.CalculateHash(crc32, buffer, bytesRead);
                } while (bytesRead == BufferSize);
                crc32 ^= Crc32Hash.DefaultSeed;
            }
            return(crc32);
        }