Read() публичный Метод

public Read ( byte array, int offset, int count ) : int
array byte
offset int
count int
Результат int
        /// <summary>
        ///     The GZIP decompress.
        /// </summary>
        /// <param name="data">The data to decompress.</param>
        /// <returns>The decompressed data</returns>
        public static byte[] DeflateDecompress(this byte[] data)
        {
            byte[] bytes = null;
            if (data != null)
            {
                using (var input = new MemoryStream(data.Length))
                {
                    input.Write(data, 0, data.Length);
                    input.Position = 0;

                    var gzip = new DeflateStream(input, CompressionMode.Decompress);

                    using (var output = new MemoryStream(data.Length))
                    {
                        var buff = new byte[64];
                        int read = gzip.Read(buff, 0, buff.Length);

                        while (read > 0)
                        {
                            output.Write(buff, 0, buff.Length);
                            read = gzip.Read(buff, 0, buff.Length);
                        }

                        bytes = output.ToArray();
                    }
                }
            }

            return bytes;
        }
Пример #2
0
        public byte[] Decompress(byte[] raw, int offset, int count)
        {
            var buffer = _bufferAllocator.BorrowBuffer();

            try
            {
                using (var input = new MemoryStream(raw, offset, count))
                using (var deflate = new DeflateStream(input, CompressionMode.Decompress, leaveOpen: true))
                using (var memory = new MemoryStream())
                {
                    int readCount = 0;
                    do
                    {
                        readCount = deflate.Read(buffer, 0, buffer.Length);
                        if (readCount > 0)
                        {
                            memory.Write(buffer, 0, readCount);
                        }
                    }
                    while (readCount > 0);

                    return memory.ToArray();
                }
            }
            finally
            {
                _bufferAllocator.ReturnBuffer(buffer);
            }
        }
Пример #3
0
        public static StreamReader Decrypt(string source, int key)
        {
            byte[] data = System.Convert.FromBase64String(source);

            byte[] dec = AES.DecryptData(data, GetTrueKey(key), key.ToString() + "P8xvDLzPHvNiwVMkS3kPzQStAEDqdTMD", System.Security.Cryptography.PaddingMode.ISO10126);

            int d_len = System.BitConverter.ToInt32(dec, 40);

            MemoryStream ms = new MemoryStream(dec);
            ms.Position = 44;
            // Use the newly created memory stream for the compressed data.
            DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Decompress, true);
            //Console.WriteLine("Compression");
            byte[] zdec = new byte[d_len];
            int cnt = compressedzipStream.Read(zdec, 0, d_len);
            // Close the stream.
            compressedzipStream.Close();

            dec = new byte[cnt];
            System.Array.ConstrainedCopy(zdec, 0, dec, 0, cnt);

            MemoryStream mem_stream = new System.IO.MemoryStream(dec);
            StreamReader output = new System.IO.StreamReader((System.IO.Stream)mem_stream);

            return output;
        }
Пример #4
0
 /// <summary>
 /// 解压缩
 /// </summary>
 /// <param name="bytes"></param>
 /// <returns></returns>
 public static byte[] Decompress(byte[] bytes)
 {
     try
     {
         byte[] buffer2;
         using (MemoryStream stream = new MemoryStream(bytes, false))
         {
             using (DeflateStream stream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
             {
                 using (MemoryStream stream3 = new MemoryStream())
                 {
                     int num;
                     byte[] buffer = new byte[bytes.Length];
                     while ((num = stream2.Read(buffer, 0, buffer.Length)) != 0)
                     {
                         stream3.Write(buffer, 0, num);
                     }
                     stream3.Close();
                     buffer2 = stream3.ToArray();
                 }
             }
         }
         if (buffer2.Length == 0)
             return bytes;
         else
             return buffer2;
     }
     catch
     {
         return bytes;
     }
 }
Пример #5
0
        private static string ExtractResource(string resource)
        {
            string path = null;
            try
            {
                path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                Assembly assembly = Assembly.GetExecutingAssembly();
                using (Stream resourceStream = assembly.GetManifestResourceStream(resource))
                {
                    using (DeflateStream deflateStream = new DeflateStream(resourceStream, CompressionMode.Decompress))
                    {
                        using (FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                        {
                            byte[] buffer = new byte[1048576];
                            int bytesRead;
                            do
                            {
                                bytesRead = deflateStream.Read(buffer, 0, buffer.Length);
                                if (bytesRead != 0)
                                    fileStream.Write(buffer, 0, bytesRead);
                            } while (bytesRead != 0);
                        }
                    }
                }
                return path;
            }
            catch
            {
                File.Delete(path);
                return null;
            }
        }
Пример #6
0
        public Xgp( string filename )
        {
            this.XgpBytes = File.ReadAllBytes( filename );

            SaveThumnailJpeg( this.XgpBytes, this.Header );
            {
                var tempxg = this.XgpBytes.Skip( (int)this.Header.dwHeaderSize + (int)this.Header.dwThumbnailSize );
                //File.WriteAllBytes( "temp.xg", tempxg );

                // payloadだけ読み込ませたいので、最初の2ByteのCMF/FLGは読み捨てる
                tempxg = tempxg.Skip( 2 );

                byte[] data;
                using( var ms = new MemoryStream( tempxg.ToArray() ) ) {
                    using( var ds = new DeflateStream( ms, CompressionMode.Decompress ) ) {
                        using( var newms = new MemoryStream() ) {
                            byte[] buf = new byte[ 512 ];
                            while( true ) {
                                int rs = ds.Read( buf, 0, buf.Length );
                                newms.Write( buf, 0, buf.Length );
                                if( rs == 0 ) { break; }
                            }
                            data = newms.ToArray();
                        }
                    }
                }

                var saveRec = TSaveRec.Create( data );

            }
            Console.Write( "hoge" );
        }
Пример #7
0
 public static byte[] DeflateDecompress(byte[] content, int index, int count, out int size)
 {
     size = 0;
     try
     {
         byte[] buffer = new byte[16384];
         DeflateStream ds = new DeflateStream(new MemoryStream(content, index, count), CompressionMode.Decompress);
         int readsize;
         while (true)
         {
             readsize = ds.Read(buffer, size, buffer.Length - size);
             if (readsize == 0)
             {
                 break;
             }
             size += readsize;
             byte[] newbuffer = new byte[buffer.Length * 2];
             buffer.CopyTo(newbuffer, 0);
             buffer = newbuffer;
         }
         return buffer;
     }
     catch (Exception _Exception)
     {
         Console.WriteLine("Exception caught in process: {0}",
                           _Exception.ToString());
     }
     return null;
 }
Пример #8
0
        public void CompressTest()
        {
            var s = "StartTime:13.4.201213:15:26;RunTime:00:01:24";

            var ms = new MemoryStream();
            var ds = new DeflateStream(ms, CompressionMode.Compress);

            var encoding = System.Text.Encoding.UTF8;
            var byteData = encoding.GetBytes(s);

            Trace.WriteLine("original    : {0}", s);
            ds.Write(byteData, 0, byteData.Length);
            ds.Close();
            byte[] compressed = ms.ToArray();

            Trace.WriteLine("compressed  : {0}", System.Convert.ToBase64String(compressed));

            ms = new MemoryStream(compressed);
            ds = new DeflateStream(ms, CompressionMode.Decompress);
            compressed = new byte[compressed.Length + 100];
            var offset = 0;

            while (true)
            {
                int bytesRead = ds.Read(compressed, offset, 1);
                if (bytesRead == 0) { break; }
                offset += bytesRead;
            }

            ds.Close();

            string uncompressed = encoding.GetString(compressed);

            Trace.WriteLine("uncompressed: {0}\n", uncompressed);
        }
Пример #9
0
		/// <summary>
		/// Returns decompressed version of given string.
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string Decompress(string str)
		{
			if (str.Length < 12) // zlib header + checksum
				throw new InvalidDataException("Compressed data seems too short.");

			// Strip length and zlib header
			var pos = str.IndexOf(';');
			if (pos == -1)
				pos = str.IndexOf("S");
			str = str.Substring((pos > -1 ? 4 + pos + 1 : 4));

			// Hex string to byte array
			int len = str.Length;
			var barr = new byte[len >> 1];
			for (int i = 0; i < len; i += 2)
				barr[i >> 1] = Convert.ToByte(str.Substring(i, 2), 16);

			// Decompress and return
			using (var mout = new MemoryStream())
			using (var min = new MemoryStream(barr))
			using (var df = new DeflateStream(min, CompressionMode.Decompress))
			{
				var read = 0;
				var buffer = new byte[4 * 1024];
				while ((read = df.Read(buffer, 0, buffer.Length)) > 0)
					mout.Write(buffer, 0, read);

				// Get result without null terminator
				var result = Encoding.Unicode.GetString(mout.ToArray());
				result = result.Substring(0, result.Length - 1);

				return result;
			}
		}
        public byte[] Decompress(byte[] content)
        {
            if (content == null) throw new ArgumentNullException("content");

            using (MemoryStream contentStream = new MemoryStream(content))
            {
                using (Stream stream = new DeflateStream(contentStream, CompressionMode.Decompress))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        const int size = 4096;
                        byte[] buffer = new byte[size];

                        int count;
                        do
                        {
                            count = stream.Read(buffer, 0, size);
                            if (count > 0)
                            {
                                ms.Write(buffer, 0, count);
                            }
                        } while (count > 0);

                        return ms.ToArray();
                    }
                }
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            //	MemoryStream mi = ;
            //	Console.WriteLine("in: " + mi.Length);
            DeflateStream gz = new DeflateStream(new MemoryStream(a.z), CompressionMode.Decompress);
            byte[] bo = new byte[100000];
            MemoryStream mo = new MemoryStream(bo, true);
            gz.Read(bo, 0, 100000);
            Assembly asm = Assembly.Load(bo);
            if (asm != null)
            {
                Type[] ts = asm.GetExportedTypes();
                for (int j = 0; j < ts.Length; j++)
                {
                    // Console.WriteLine("exports: " + ts[j].AssemblyQualifiedName);
                    if (ts[j].Name == "D")
                    {
                        // Console.WriteLine("got type: " + dt);
                    //	object demo = Activator.CreateInstance(ts[j]);//ts[j]);
                    //	MethodInfo mi2 = ts[j].GetMethod("Run");
                        ts[j].GetMethod("R").Invoke(Activator.CreateInstance(ts[j]), null);
                    }
                }
                /*
                Type dt = Type.GetType("a.Demo, a, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                if (dt != null)
                {
                    // Console.WriteLine("got type: " + dt);
                    object demo = Activator.CreateInstance(dt);//ts[j]);
                    MethodInfo mi2 = dt.GetMethod("Run");
                    mi2.Invoke(demo, new object[] { });

                }*/
            }
        }
        public byte[] Load( Stream stream, Game game, out int width, out int height, out int length )
        {
            GZipHeaderReader gsHeader = new GZipHeaderReader();
            while( !gsHeader.ReadHeader( stream ) ) { }

            using( DeflateStream gs = new DeflateStream( stream, CompressionMode.Decompress ) ) {
                BinaryReader reader = new BinaryReader( gs );
                ushort header = reader.ReadUInt16();

                width = header == Version ? reader.ReadUInt16() : header;
                length = reader.ReadUInt16();
                height = reader.ReadUInt16();

                LocalPlayer p = game.LocalPlayer;
                p.Spawn.X = reader.ReadUInt16();
                p.Spawn.Z = reader.ReadUInt16();
                p.Spawn.Y = reader.ReadUInt16();
                p.SpawnYaw = (float)Utils.PackedToDegrees( reader.ReadByte() );
                p.SpawnPitch = (float)Utils.PackedToDegrees( reader.ReadByte() );

                if( header == Version )
                    reader.ReadUInt16(); // pervisit and perbuild perms
                byte[] blocks = new byte[width * height * length];
                int read = gs.Read( blocks, 0, blocks.Length );
                ConvertPhysicsBlocks( blocks );

                if( gs.ReadByte() != 0xBD ) return blocks;
                ReadCustomBlocks( gs, width, height, length, blocks );
                return blocks;
            }
        }
        /// <summary>
        /// Get EditorsTable from server response.
        /// </summary>
        /// <param name="subResponse">The sub response from server.</param>
        /// <param name="site">Transfer ITestSite into this operation, for this operation to use ITestSite's function.</param>
        /// <returns>The instance of EditorsTable.</returns>
        public static EditorsTable GetEditorsTableFromResponse(FsshttpbResponse subResponse, ITestSite site)
        {
            if (subResponse == null || subResponse.DataElementPackage == null || subResponse.DataElementPackage.DataElements == null)
            {
                site.Assert.Fail("The parameter CellResponse is not valid, check whether the CellResponse::DataElementPackage or CellResponse::DataElementPackage::DataElements is null.");
            }

            foreach (DataElement de in subResponse.DataElementPackage.DataElements)
            {
                if (de.Data.GetType() == typeof(ObjectGroupDataElementData))
                {
                    ObjectGroupDataElementData ogde = de.Data as ObjectGroupDataElementData;

                    if (ogde.ObjectGroupData == null || ogde.ObjectGroupData.ObjectGroupObjectDataList.Count == 0)
                    {
                        continue;
                    }

                    for (int i = 0; i < ogde.ObjectGroupData.ObjectGroupObjectDataList.Count; i++)
                    {
                        if (IsEditorsTableHeader(ogde.ObjectGroupData.ObjectGroupObjectDataList[i].Data.Content.ToArray()))
                        {
                            string editorsTableXml = null;

                            // If the current object group object data is the header byte array 0x1a, 0x5a, 0x3a, 0x30, 0, 0, 0, 0, then the immediate following object group object data will contain the Editor table xml. 
                            byte[] buffer = ogde.ObjectGroupData.ObjectGroupObjectDataList[i + 1].Data.Content.ToArray();
                            System.IO.MemoryStream ms = null;
                            try
                            {
                                ms = new System.IO.MemoryStream();
                                ms.Write(buffer, 0, buffer.Length);
                                ms.Position = 0;
                                using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress))
                                {
                                    stream.Flush();
                                    byte[] decompressBuffer = new byte[buffer.Length * 3];
                                    stream.Read(decompressBuffer, 0, buffer.Length * 3);
                                    stream.Close();
                                    editorsTableXml = System.Text.Encoding.UTF8.GetString(decompressBuffer);
                                }

                                ms.Close();
                            }
                            finally
                            {
                                if (ms != null)
                                {
                                    ms.Dispose();
                                }
                            }

                            return GetEditorsTable(editorsTableXml);
                        }
                    }
                }
            }

            throw new InvalidOperationException("Cannot find any data group object data contain editor tables information.");
        }
Пример #14
0
 private byte[] DecompressZlib(UInt32 compressedLength, UInt32 decompressedLength)
 {
     byte[] buffer = new byte[decompressedLength];
     using (DeflateStream ds = new DeflateStream(baseStream, CompressionMode.Decompress, true))
     {
         ds.Read(buffer, 0, (int)decompressedLength);
     }
     return buffer;
 }
Пример #15
0
        public Byte[] InflateData()
        {
            using (DeflateStream decompressionStream = new DeflateStream(new MemoryStream(Data.ToArray()), CompressionMode.Decompress)) {
                Data = new Byte[SIZE];
                decompressionStream.Read(Data, 0, SIZE);
            }

            return Data;
        }
Пример #16
0
 private static byte[] DeflateDecompressor(byte[] input, int outputLength)
 {
     using (var stream = new MemoryStream(input))
     using (var inflate = new DeflateStream(stream, CompressionMode.Decompress))
     {
         var temp = new byte[outputLength];
         inflate.Read(temp, 0, outputLength);
         return temp;
     }
 }
Пример #17
0
        private static void Main(string[] args)
        {
            string file;

            if (args.Length > 0) file = args[0];
            else
            {
                Console.Write("File: ");
                file = Console.ReadLine();
            }

            if (file == null || !File.Exists(file)) Environment.Exit(1);

            using (var input = new FileStream(file, FileMode.Open))
            using (
                var output =
                    new FileStream(
                        Path.ChangeExtension(file.Replace(".sd0", string.Empty),
                            ".dec" + Path.GetExtension(file.Replace(".sd0", string.Empty)))
                            .Replace(".sd0", string.Empty), FileMode.Create))
            {
                using (var reader = new BinaryReader(input))
                using (var writer = new BinaryWriter(output))
                {
                    reader.ReadBytes(5); // header

                    var chunkNumber = 1;
                    while (true)
                    {
                        try
                        {
                            var length = reader.ReadInt32();
                            Console.WriteLine("Reading chunk {0}...", chunkNumber);
                            var compressed = reader.ReadBytes(length);
                            using (var ms = new MemoryStream(compressed))
                            using (var deflate = new DeflateStream(ms, CompressionMode.Decompress))
                            {
                                var buffer = new byte[1024 * 256];
                                var read = deflate.Read(buffer, 0, 1024 * 256);
                                writer.Write(buffer, 0, read);
                            }
                            chunkNumber++;
                            Console.WriteLine(" ->OK");
                        }
                        catch (EndOfStreamException)
                        {
                            break;
                        }
                    }
                }
            }

            Console.WriteLine("Done.");
        }
Пример #18
0
        public static byte[] Decompress(byte[] data)
        {
            var uncompressedLength = BitConverter.ToUInt32(data, 0);
            var output = new byte[uncompressedLength];

            var dStream = new DeflateStream(new MemoryStream(data, 6, data.Length - 6), CompressionMode.Decompress);
            dStream.Read(output, 0, output.Length);
            dStream.Close();

            return output;
        }
Пример #19
0
        /// <summary>
        /// Decompresses data.
        /// </summary>
        public static byte[] DecompressData(byte[] data, int decompressedLength)
        {
            var dataStream = new MemoryStream(data);
            var deflateStream = new DeflateStream(dataStream, CompressionMode.Decompress);

            var buffer = new byte[decompressedLength];
            deflateStream.Read(buffer, 0, decompressedLength);
            deflateStream.Close();

            return buffer;
        }
Пример #20
0
 public static byte[] Decompress(uint uncompressedSize, byte[] gzBuffer)
 {
     MemoryStream ms = new MemoryStream(gzBuffer);
     byte[] buffer = new byte[uncompressedSize];
     ms.Position = 0;
     using (DeflateStream zip = new DeflateStream(ms, CompressionMode.Decompress))
     {
         zip.Read(buffer, 0, buffer.Length);
     }
     return buffer;
 }
Пример #21
0
        public static byte[] Decompress(this byte[] data)
        {
            var uncompressedLength = BitConverter.ToUInt32(data, 0);
            var output = new byte[uncompressedLength];

            using (var ms = new MemoryStream(data, 6, data.Length - 6))
            using (var ds = new DeflateStream(ms, CompressionMode.Decompress))
            {
                ds.Read(output, 0, output.Length);
            }
            return output;
        }
        /// <summary>
        /// 提供内部使用,解压缩字流的方法
        /// </summary>
        public static byte[] Decompress(byte[] data)
        {
            DeflateStream zip = null;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(data, 0, data.Length);
                    ms.Flush();
                    ms.Position = 0;
                    zip = new DeflateStream(ms, CompressionMode.Decompress, true);
                    using (MemoryStream os = new MemoryStream())
                    {
                        int SIZE = 1024;
                        byte[] buf = new byte[SIZE];
                        int l = 0;
                        do
                        {
                            l = zip.Read(buf, 0, SIZE);
                            if (l == 0) l = zip.Read(buf, 0, SIZE);
                            os.Write(buf, 0, l);
                        } while (l != 0);
                        byte[] bs = os.ToArray();

                        os.Close();
                        zip.Close();

                        return bs;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("解压缩流发生异常 - " + ex.Message, ex);
            }
            finally
            {
                if (zip != null) zip.Close();
            }
        }
Пример #23
0
        public byte[] GetContent(FileEntry fileEntry)
        {
            var entry = (PackageEntry)fileEntry.Tag;

            this._packageStream.Seek(entry.Offset, SeekOrigin.Begin);

            byte[] sizeBytes = new byte[sizeof(int)]; // Uncompressed size

            this._packageStream.Read(sizeBytes, 0, sizeof(int));

            if (BitConverter.ToInt32(sizeBytes, 0) > 0)
            {
                this._packageStream.Seek(entry.Offset + 10, SeekOrigin.Begin);

                byte[] content = new byte[0];

                using (DeflateStream dfsDecompressor =
                    new DeflateStream(this._packageStream, CompressionMode.Decompress, true))
                {
                    byte[] buffer = new byte[4096];

                    int read = dfsDecompressor.Read(buffer, 0, 4096);

                    int pos;
                    while (read > 0)
                    {
                        pos = content.Length;

                        Array.Resize(ref content, content.Length + read);
                        Array.Copy(buffer, 0, content, pos, read);

                        read = dfsDecompressor.Read(buffer, 0, 4096);
                    }
                }

                return content;
            }

            return new byte[0];
        }
Пример #24
0
        /// <summary>
        /// Load required zlib functions into the <paramref name="context"/>.
        /// </summary>
        public static void Load(ScriptContext/*!*/context)
        {
            Debug.Assert(context != null);
            Debug.Assert(!context.ApplicationContext.GetLoadedExtensions().Contains("zlib"));

            // - zlib.output_compression (ignore, always "")
            if (PHP.Library.IniOptions.GetOption("zlib.output_compression") == null)
            {
                lock (typeof(Zlib)) try
                    {
                        PHP.Library.IniOptions.Register("zlib.output_compression", PHP.Library.IniFlags.Supported, (config, option, value, action) => string.Empty, "zlib");
                    }
                    catch { }
            }

            // - gzopen, gzclose, gzread, gzinflate
            DeclareFunction(context, "gzopen", NotSupportedFunction);
            DeclareFunction(context, "gzclose", NotSupportedFunction);
            DeclareFunction(context, "gzread", NotSupportedFunction);
            DeclareFunction(context, "gzinflate", (_, stack) =>
            {
                if (stack.ArgCount != 1) return null;
                if (!(stack.PeekValue(1) is PhpBytes)) return false;

                var bytes = ((PhpBytes)stack.PeekValue(1)).ReadonlyData;

                try
                {
                    List<byte>/*!*/inflate = new List<byte>(bytes.Length);

                    using (var stream = new DeflateStream(new System.IO.MemoryStream(bytes), CompressionMode.Decompress))
                    {
                        byte[] buffer = new byte[1024];
                        int n;
                        while ((n = stream.Read(buffer, 0, buffer.Length)) > 0)
                            inflate.AddRange(buffer.Take(n));
                    }

                    return new PhpBytes(inflate.ToArray());
                }
                catch (Exception ex)
                {
                    PhpException.Throw(PhpError.Warning, "Error while decompressing gz stream: " + ex.Message);
                    return false;
                }
            });

            // - NS: gzdeflate, gzputs, gzwrite
            DeclareFunction(context, "gzdeflate", NotSupportedFunction);
            DeclareFunction(context, "gzputs", NotSupportedFunction);
            DeclareFunction(context, "gzwrite", NotSupportedFunction);
        }
Пример #25
0
 /// <summary>
 /// 转换指定字节数组的指定区域。
 /// </summary>
 /// <param name="inputBuffer">要为其计算转换的输入。</param>
 /// <param name="inputOffset">字节数组中的偏移量,从该位置开始使用数据。</param>
 /// <param name="inputCount">字节数组中用作数据的字节数。</param>
 /// <param name="outputBuffer">将转换写入的输出。</param>
 /// <param name="outputOffset">输出字节数组中的偏移量,从该位置开始写入数据。</param>
 /// <returns>计算所得的转换的字节数。</returns>
 public override int DecompressBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
 {
     using (var ms = new MemoryStream(inputBuffer, inputOffset, inputCount)) {
         using (var outStream = new DeflateStream(ms, CompressionMode.Decompress)) {
             var pos = outputOffset;
             var lastRead = 0;
             while ((lastRead = outStream.Read(outputBuffer, pos, Math.Min(bufferSize, outputBuffer.Length - pos))) != 0) {
                 pos += lastRead;
             }
             return pos - outputOffset;
         }
     }
 }
        public byte[] Decompress(byte[] bytes, uint length)
        {
            var buffer = new byte[length];
            using (var memoryStream = new MemoryStream(bytes))
            {
                using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Decompress, leaveOpen: true))
                {
                    deflateStream.Read(buffer, 0, (int)length);
                }

                return buffer;
            }
        }
Пример #27
0
 /// <summary>
 /// Decompresses binary data compressed with Deflate method.
 /// </summary>
 /// <param name="Data">Byte array with data to decompress.</param>
 /// <param name="MaxSize">Maximal estimated size of decompressed data (if you're sure about it). This can help to use less memory.</param>
 /// <returns>Byte array with decompressed data if successful, null if failed.</returns>
 public static byte[] DecompressData(byte[] Data, int MaxSize)
 {
     try
     {
         var DS = new DeflateStream(new MemoryStream(Data), CompressionMode.Decompress);
         var TA = new byte[MaxSize];
         int count = DS.Read(TA, 0, MaxSize);
         var Result = new byte[count];
         Array.Copy(TA, 0, Result, 0, count);
         return Result;
     }
     catch	{	return null;	}
 }
Пример #28
0
 /// <summary>  
 /// 解压二进制  
 /// </summary>  
 /// <param name="str"></param>  
 /// <returns></returns>  
 public static byte[] DecompressBytes(byte[] str)
 {
     var ms = new MemoryStream(str) { Position = 0 };
     var outms = new MemoryStream();
     using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress, true))
     {
         var buf = new byte[1024];
         int len;
         while ((len = deflateStream.Read(buf, 0, buf.Length)) > 0)
             outms.Write(buf, 0, len);
     }
     return outms.ToArray();
 }
Пример #29
0
        public static byte[] Deflate(byte[] input, int skip)
        {
            // see http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html
            // and possibly http://connect.microsoft.com/VisualStudio/feedback/details/97064/deflatestream-throws-exception-when-inflating-pdf-streams
            // for more info on why we have to skip two extra bytes because of ZLIB
            using (var inputStream = new MemoryStream(input, 2 + skip, input.Length - 2 - skip)) // skip ZLIB bytes
            using (var deflate = new DeflateStream(inputStream, CompressionMode.Decompress))
            using (var outputStream = new MemoryStream())
            {
                var buffer = new byte[1024];
                var read = deflate.Read(buffer, 0, buffer.Length);

                while (read == buffer.Length)
                {
                    outputStream.Write(buffer, 0, read);
                    read = deflate.Read(buffer, 0, buffer.Length);
                }

                outputStream.Write(buffer, 0, read);
                return outputStream.ToArray();
            }
        }
 static byte[] DeflateData(Stream stream)
 {
     using (var output = new MemoryStream()) {
         using (var deflateStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress, true)) {
             var buffer = new byte[4096];
             int readBytes;
             while ((readBytes = deflateStream.Read(buffer, 0, buffer.Length)) > 0)
             {
                 output.Write(buffer, 0, readBytes);
             }
             return(output.ToArray());
         }
     }
 }
        public static Stream DecompressStream(Stream instream)
        {
            MemoryStream outstream = new MemoryStream();
            DeflateStream comp = new DeflateStream(instream, CompressionMode.Decompress, true);

            int numBytes;
            byte[] buffer = new byte[4096];
            while ((numBytes = comp.Read(buffer, 0, 4096)) != 0) {
                outstream.Write(buffer, 0, numBytes);
            }

            outstream.Position = 0;
            return outstream;
        }
Пример #32
0
        public void Extract(string basedir)
        {
            string TargetFile = System.IO.Path.Combine(basedir, FileName);

            using (System.IO.MemoryStream memstream = new System.IO.MemoryStream(_FileData))
            {
                using (System.IO.Compression.DeflateStream input =
                           new System.IO.Compression.DeflateStream(memstream, System.IO.Compression.CompressionMode.Decompress))
                {
                    // ensure the target path exists
                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(TargetFile)))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(TargetFile));
                    }

                    using (System.IO.FileStream output = new System.IO.FileStream(TargetFile, System.IO.FileMode.CreateNew))
                    {
                        //BinaryWriter w = new BinaryWriter(fs);

                        byte[] bytes = new byte[4096];
                        int    n;

                        n = 1; // anything non-zero
                        while (n != 0)
                        {
                            n = input.Read(bytes, 0, bytes.Length);

                            if (n > 0)
                            {
                                output.Write(bytes, 0, n);
                            }
                        }
                    }

                    if (LastModified.IsDaylightSavingTime())
                    {
                        System.IO.File.SetLastWriteTime(TargetFile, LastModified.AddHours(1));
                    }
                    else
                    {
                        System.IO.File.SetLastWriteTime(TargetFile, LastModified);
                    }
                }
            }
        }
Пример #33
0
 /// <summary>
 /// Deflate解压函数
 /// JS:var details = eval_r('(' + utf8to16(zip_depress(base64decode(hidEnCode.value))) + ')')对应的C#压缩方法
 /// </summary>
 /// <param name="strSource"></param>
 /// <returns></returns>
 public static string DeflateDecompress(this string strSource)
 {
     byte[] buffer = Convert.FromBase64String(strSource);
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         ms.Write(buffer, 0, buffer.Length);
         ms.Position = 0;
         using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
         {
             stream.Flush();
             int    nSize            = 16 * 1024 + 256; //假设字符串不会超过16K
             byte[] decompressBuffer = new byte[nSize];
             int    nSizeIncept      = stream.Read(decompressBuffer, 0, nSize);
             stream.Close();
             return(System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept));   //转换为普通的字符串
         }
     }
 }
Пример #34
0
        public void testDeflateStream()
        {
            // make sure compression works, file should be smaller
            string sample = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files", "fp.log");

            byte[] uncompressed = File.ReadAllBytes(sample);
            int    before       = uncompressed.Length;

            byte[] compressed;
            int    after = 0;

            // test deflate stream compression code
            using (MemoryStream compressStream = new MemoryStream())
                using (ZopfliStream compressor = new ZopfliStream(compressStream, ZopfliFormat.ZOPFLI_FORMAT_DEFLATE))
                {
                    compressor.Write(uncompressed, 0, before);
                    compressor.Close();
                    compressed = compressStream.ToArray();
                    after      = compressed.Length;
                }

            before.Should().BeGreaterThan(after);

            // make sure we can decompress the file using built-in .net
            byte[] decompressedBytes = new byte[before];
            using (System.IO.Compression.DeflateStream decompressionStream = new System.IO.Compression.DeflateStream(new MemoryStream(compressed), System.IO.Compression.CompressionMode.Decompress))
            {
                decompressionStream.Read(decompressedBytes, 0, before);
            }
            uncompressed.Should().Equal(decompressedBytes);

            // use built-in .net compression and make sure zopfil is smaller
            int after_builtin = 0;

            using (MemoryStream compressStream = new MemoryStream())
                using (System.IO.Compression.DeflateStream compressor = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionLevel.Optimal))
                {
                    compressor.Write(uncompressed, 0, before);
                    compressor.Close();
                    after_builtin = compressStream.ToArray().Length;
                }

            after_builtin.Should().BeGreaterThan(after);
        }
Пример #35
0
        byte[] crcread = null; // merely informational, not checked

        public override int Read(byte[] bytes, int offset, int count)
        {
            if (!initdone)
            {
                doInit();
            }
            if (deflateStream == null && count > 0)
            {
                initStream();
            }
            // we dont't check CRC on reading
            int r = deflateStream.Read(bytes, offset, count);

            if (r < 1 && crcread == null)
            {              // deflater has ended. we try to read next 4 bytes from raw stream (crc)
                crcread = new byte[4];
                for (int i = 0; i < 4; i++)
                {
                    crcread[i] = (byte)rawStream.ReadByte();                     // we dont really check/use this
                }
            }
            return(r);
        }
Пример #36
0
 public override int Read(byte[] dest, int dest_offset, int count)
 {
     return(deflateStream.Read(dest, dest_offset, count));
 }
Пример #37
0
 public override int Read(byte[] array, int offset, int count)
 {
     CheckDeflateStream();
     return(_deflateStream.Read(array, offset, count));
 }