System.IO.Stream.Read(byte[], int, int)

Here are the examples of the csharp api System.IO.Stream.Read(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4079 Examples 7

19 View Source File : DisposeActionStream.cs
License : MIT License
Project Creator : 0x0ade

public override int Read(byte[] buffer, int offset, int count) => Inner.Read(buffer, offset, count);

19 View Source File : PositionAwareStream.cs
License : MIT License
Project Creator : 0x0ade

public override int Read(byte[] buffer, int offset, int count) {
            int read = Inner.Read(buffer, offset, count);
            if (read > 0)
                _Position += read;
            return read;
        }

19 View Source File : HeifReaderFactory.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

private static byte[] CopyStreamToByteArray(Stream stream)
        {
            byte[] buffer = new byte[stream.Length];

            int offset = 0;
            int remaining = buffer.Length;

            while (remaining > 0)
            {
                int bytesRead = stream.Read(buffer, offset, remaining);

                if (bytesRead == 0)
                {
                    throw new EndOfStreamException();
                }

                offset += bytesRead;
                remaining -= bytesRead;
            }

            return buffer;
        }

19 View Source File : HeifStreamReader.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

protected override bool ReadCore(IntPtr data, long count)
        {
            long totalBytesRead = 0;
            long remaining = count;

            while (remaining > 0)
            {
                int streamBytesRead = this.stream.Read(this.streamBuffer, 0, (int)Math.Min(MaxReadBufferSize, remaining));

                if (streamBytesRead == 0)
                {
                    break;
                }

                Marshal.Copy(this.streamBuffer, 0, new IntPtr(data.ToInt64() + totalBytesRead), streamBytesRead);

                totalBytesRead += streamBytesRead;
                remaining -= streamBytesRead;
            }

            return remaining == 0;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

private void FillBuffer(int minBytes)
        {
            int bytesUnread = this.readLength - this.readOffset;

            if (bytesUnread > 0)
            {
                Buffer.BlockCopy(this.buffer, this.readOffset, this.buffer, 0, bytesUnread);
            }

            int numBytesToRead = this.bufferSize - bytesUnread;
            int numBytesRead = bytesUnread;
            do
            {
                int n = this.stream.Read(this.buffer, numBytesRead, numBytesToRead);

                if (n == 0)
                {
                    throw new EndOfStreamException();
                }

                numBytesRead += n;
                numBytesToRead -= n;

            } while (numBytesRead < minBytes);

            this.readOffset = 0;
            this.readLength = numBytesRead;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

private int ReadInternal(byte[] bytes, int offset, int count)
        {
            if (count == 0)
            {
                return 0;
            }

            if ((this.readOffset + count) <= this.readLength)
            {
                if (count <= 8)
                {
                    // Use a for loop when copying a small number of bytes.
                    for (int i = 0; i < count; i++)
                    {
                        bytes[offset + i] = this.buffer[this.readOffset + i];
                    }
                }
                else
                {
                    Buffer.BlockCopy(this.buffer, this.readOffset, bytes, offset, count);
                }
                this.readOffset += count;

                return count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = this.readLength - this.readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(this.buffer, this.readOffset, bytes, offset, bytesUnread);
                }

                // Invalidate the existing buffer.
                this.readOffset = 0;
                this.readLength = 0;

                int totalBytesRead = bytesUnread;

                totalBytesRead += this.stream.Read(bytes, offset + bytesUnread, count - bytesUnread);

                return totalBytesRead;
            }
        }

19 View Source File : StreamSegment.cs
License : MIT License
Project Creator : 0xC0000054

public override int Read(byte[] buffer, int offset, int count)
        {
            VerifyNotDisposed();

            if (count < 0)
            {
                ExceptionUtil.ThrowArgumentOutOfRangeException(nameof(count), "Must be >= 0.");
            }

            if ((this.Position + count) > this.Length)
            {
                count = (int)(this.Length - this.Position);
            }

            return this.stream.Read(buffer, offset, count);
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public int Read(byte[] bytes, int offset, int count)
        {
            if (bytes is null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return 0;
            }

            if ((readOffset + count) <= readLength)
            {
                Buffer.BlockCopy(buffer, readOffset, bytes, offset, count);
                readOffset += count;

                return count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = readLength - readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(buffer, readOffset, bytes, offset, bytesUnread);
                }

                // Invalidate the existing buffer.
                readOffset = 0;
                readLength = 0;

                int totalBytesRead = bytesUnread;

                totalBytesRead += stream.Read(bytes, offset + bytesUnread, count - bytesUnread);

                return totalBytesRead;
            }
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public byte[] ReadBytes(int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return EmptyArray<byte>.Value;
            }

            byte[] bytes = new byte[count];

            if ((readOffset + count) <= readLength)
            {
                Buffer.BlockCopy(buffer, readOffset, bytes, 0, count);
                readOffset += count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = readLength - readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(buffer, readOffset, bytes, 0, bytesUnread);
                }

                int numBytesToRead = count - bytesUnread;
                int numBytesRead = bytesUnread;
                do
                {
                    int n = stream.Read(bytes, numBytesRead, numBytesToRead);

                    if (n == 0)
                    {
                        throw new EndOfStreamException();
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;

                } while (numBytesToRead > 0);

                // Invalidate the existing buffer.
                readOffset = 0;
                readLength = 0;
            }

            return bytes;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

private void FillBuffer(int minBytes)
        {
            int bytesUnread = readLength - readOffset;

            if (bytesUnread > 0)
            {
                Buffer.BlockCopy(buffer, readOffset, buffer, 0, bytesUnread);
            }

            int numBytesToRead = bufferSize - bytesUnread;
            int numBytesRead = bytesUnread;
            do
            {
                int n = stream.Read(buffer, numBytesRead, numBytesToRead);

                if (n == 0)
                {
                    throw new EndOfStreamException();
                }

                numBytesRead += n;
                numBytesToRead -= n;

            } while (numBytesRead < minBytes);

            readOffset = 0;
            readLength = numBytesRead;
        }

19 View Source File : StreamIOCallbacks.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe int Read(IntPtr buffer, uint count, uint* bytesRead)
        {
            if (bytesRead != null)
            {
                *bytesRead = 0;
            }

            if (count == 0)
            {
                return HResult.S_OK;
            }

            try
            {
                long totalBytesRead = 0;
                long remaining = count;

                do
                {
                    int streamBytesRead = this.stream.Read(this.streamBuffer, 0, (int)Math.Min(MaxBufferSize, remaining));

                    if (streamBytesRead == 0)
                    {
                        break;
                    }

                    Marshal.Copy(this.streamBuffer, 0, new IntPtr(buffer.ToInt64() + totalBytesRead), streamBytesRead);

                    totalBytesRead += streamBytesRead;
                    remaining -= streamBytesRead;

                } while (remaining > 0);

                if (bytesRead != null)
                {
                    *bytesRead = (uint)totalBytesRead;
                }
                return HResult.S_OK;
            }
            catch (Exception ex)
            {
                this.CallbackExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                return ex.HResult;
            }
        }

19 View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054

protected override Doreplacedent OnLoad(Stream input)
        {
            Doreplacedent doc = null;
            string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            try
            {
                // Write the input stream to a temporary file for LibRaw to load.
                using (FileStream output = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    if (input.CanSeek)
                    {
                        output.SetLength(input.Length);
                    }

                    // 81920 is the largest multiple of 4096 that is under the large object heap limit (85,000 bytes).
                    byte[] buffer = new byte[81920];

                    int bytesRead;
                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, bytesRead);
                    }
                }

                doc = GetRAWImageDoreplacedent(tempFile);
            }
            finally
            {
                File.Delete(tempFile);
            }

            return doc;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public int Read(byte[] bytes, int offset, int count)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return 0;
            }

            if ((readOffset + count) <= readLength)
            {
                Buffer.BlockCopy(buffer, readOffset, bytes, offset, count);
                readOffset += count;

                return count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = readLength - readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(buffer, readOffset, bytes, offset, bytesUnread);
                }

                // Invalidate the existing buffer.
                readOffset = 0;
                readLength = 0;

                int totalBytesRead = bytesUnread;

                totalBytesRead += stream.Read(bytes, offset + bytesUnread, count - bytesUnread);

                return totalBytesRead;
            }
        }

19 View Source File : cMain.cs
License : MIT License
Project Creator : 0xPh0enix

[STAThread]
        static void Main()
        {
            replacedembly aASM = replacedembly.GetExecutingreplacedembly();

            using (Stream sResStream = aASM.GetManifestResourceStream("%RES_NAME%"))
            {
                if (sResStream == null)
                    return;

                byte[] bFile = new byte[sResStream.Length];
                sResStream.Read(bFile, 0, bFile.Length);

                bFile = Decrypt(bFile, System.Text.Encoding.Default.GetBytes("%ENC_KEY%"));

                replacedembly.Load(bFile).EntryPoint.Invoke(null, null);

            }
        }

19 View Source File : StreamEx.cs
License : MIT License
Project Creator : 13xforever

public static int ReadExact(this Stream input, byte[] buffer, int offset, int count)
        {
            var result = 0;
            int read;
            do
            {
                read = input.Read(buffer, offset, count);
                result += read;
                offset += read;
                count -= read;
            } while (count > 0 && read > 0);
            return result;
        }

19 View Source File : PkgChecker.cs
License : MIT License
Project Creator : 13xforever

public static void ReadExact(this Stream stream, byte[] buf)
        {
            var read = 0;
            var total = 0;
            do
            {
                read = stream.Read(buf, read, buf.Length - read);
                total += read;
            } while (read > 0 && total < buf.Length);
            if (total < buf.Length)
                throw new InvalidOperationException($"Expected to read {buf.Length} bytes, but could only read {total} bytes");
        }

19 View Source File : StreamDeserializeAux.cs
License : MIT License
Project Creator : 1996v

private void ReadStreamToBuffer(int len)
        {
            if (buffer.Length < position + len)
            {
                BufferResize(position + len);
            }

            int readNum = stream.Read(buffer, position, len);
            if (readNum != len)
            {
                throw new Exception();//格式错误
            }

            position += len;
        }

19 View Source File : StreamDeserializeAux.cs
License : MIT License
Project Creator : 1996v

public static byte Get(Stream stream, byte[] buffer)
            {
                byte one = ReadStreamByte(stream);

                if (one <= BssomType.MaxBlankCodeValue)
                {
                    if (one <= BssomType.MaxVarBlankCodeValue)
                    {
                        AdvanceStream(stream, buffer, one);
                    }
                    else
                    {
                        int len;
                        if (one == BssomType.BlankUInt16Code)
                        {
                            stream.Read(buffer, 0, buffer[2]);
                            len = BssomBinaryPrimitives.ReadUInt16LittleEndian(ref buffer[0]);
                        }
                        else /*if (one == BssomType.EmptyUInt32Code)*/
                        {
                            stream.Read(buffer, 0, buffer[4]);
                            len = checked((int)BssomBinaryPrimitives.ReadUInt32LittleEndian(ref buffer[0]));
                        }
                        AdvanceStream(stream, buffer, len);
                    }

                    one = ReadStreamByte(stream);
                }

                return one;
            }

19 View Source File : StreamDeserializeAux.cs
License : MIT License
Project Creator : 1996v

private static void StreamSkip(Stream stream, byte[] buffer, int size)
            {
                int readNum = stream.Read(buffer, 0, size);
                if (readNum != size)
                {
                    throw new Exception();//格式错误
                }
            }

19 View Source File : ObservableHttpData.cs
License : MIT License
Project Creator : 1iveowl

internal IObservable<byte[]> Create(IParseControl parseControl, Stream stream, TimeSpan timeout)
        {
            return Observable.Create<byte[]>(
                obs =>
                {
                    var oneByteBuffer = new byte[1];

                    while (!parseControl.IsEndOfRequest
                        && !parseControl.IsRequestTimedOut
                        && !parseControl.IsUnableToParseHttp)
                    {
                        if (stream.CanRead)
                        {
                            if (stream.Read(oneByteBuffer, 0, oneByteBuffer.Length) != 0)
                            {
                                obs.OnNext(oneByteBuffer);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    obs.OnCompleted();
                    return Disposable.Empty;
                })
                .Timeout(timeout);
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public string GetString(Encoding coding)
        {
            StringBuilder str = new StringBuilder();
            Stream sr = ResponseContent;
            sr.Seek(0, SeekOrigin.Begin);
            byte[] data = new byte[1024 * 1024];
            int readcount = sr.Read(data, 0, data.Length);
            while (readcount > 0)
            {
                str.Append(coding.GetString(data, 0, readcount));
                readcount = sr.Read(data, 0, data.Length);
            }
            return str.ToString();
        }

19 View Source File : RedisIO.cs
License : MIT License
Project Creator : 2881099

public int Read(byte[] data, int offset, int count)
        {
            lock (_streamLock)
                return Stream.Read(data, offset, count);
        }

19 View Source File : Compression.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static void CopyTo(Stream src, Stream dest)
        {
            byte[] bytes = new byte[4096];

            int cnt;

            while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
            {
                dest.Write(bytes, 0, cnt);
            }
        }

19 View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz

public byte[] GetChunkData(RiffChunk chunk)
        {
            long oldPosition = waveStream.Position;
            waveStream.Position = chunk.StreamPosition;
            byte[] data = new byte[chunk.Length];
            waveStream.Read(data, 0, data.Length);
            waveStream.Position = oldPosition;
            return data;
        }

19 View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz

public override int Read(byte[] array, int offset, int count)
        {
            if (count % waveFormat.BlockAlign != 0)
            {
                throw new ArgumentException(String.Format("Must read complete blocks: requested {0}, block align is {1}", count, this.WaveFormat.BlockAlign));
            }
            // sometimes there is more junk at the end of the file past the data chunk
            if (Position + count > dataChunkLength)
            {
                count = dataChunkLength - (int)Position;
            }
            return waveStream.Read(array, offset, count);
        }

19 View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo

protected virtual Stream HttpGetURI(string uri, int tries = 1)
        {
            AppendApiKey(ref uri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "GET";
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("GET " + uri + " TRY: " + tries);

            try
            {
                MemoryStream memStream;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    memStream = new MemoryStream();

                    byte[] buffer = new byte[1024];
                    int byteCount;
                    int total = 0;

                    var ns = response.GetResponseStream();
                    do
                    {
                        byteCount = ns.Read(buffer, 0, buffer.Length);
                        memStream.Write(buffer, 0, byteCount);

                        total += byteCount;
                    } while (byteCount > 0);
                    request.Abort();
                }

                return memStream;
            }
            catch (WebException)
            {
                if (--tries == 0)
                    throw;

                return HttpGetURI(uri, tries);
            }
        }

19 View Source File : ExtendUtility.cs
License : MIT License
Project Creator : 3wz

public static void CopyTo(this Stream input, Stream output)
    {
        byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
        int bytesRead;

        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
    }

19 View Source File : CodedInputStream.cs
License : MIT License
Project Creator : 404Lcc

private void SkipImpl(int amountToSkip)
        {
            if (input.CanSeek)
            {
                long previousPosition = input.Position;
                input.Position += amountToSkip;
                if (input.Position != previousPosition + amountToSkip)
                {
                    throw InvalidProtocolBufferException.TruncatedMessage();
                }
            }
            else
            {
                byte[] skipBuffer = new byte[Math.Min(1024, amountToSkip)];
                while (amountToSkip > 0)
                {
                    int bytesRead = input.Read(skipBuffer, 0, Math.Min(skipBuffer.Length, amountToSkip));
                    if (bytesRead <= 0)
                    {
                        throw InvalidProtocolBufferException.TruncatedMessage();
                    }
                    amountToSkip -= bytesRead;
                }
            }
        }

19 View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc

public bool Downloading()
        {
            if (File.Exists(downloadData.path))
            {
                currentSize = downloadData.size;
                return true;
            }
            long position = 0;
            string tempPath = downloadData.path + ".temp";
            if (File.Exists(tempPath))
            {
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    position = fileStream.Length;
                    fileStream.Seek(position, SeekOrigin.Current);
                    if (position == downloadData.size)
                    {
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        File.Move(tempPath, downloadData.path);
                        currentSize = position;
                        return true;
                    }
                }
            }
            else
            {
                PathUtil.GetPath(PathType.PersistentDataPath, Path.GetDirectoryName(downloadData.path));
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    HttpWebRequest httpWebRequest = null;
                    HttpWebResponse httpWebResponse = null;
                    try
                    {
                        httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
                        httpWebRequest.ReadWriteTimeout = readWriteTimeout;
                        httpWebRequest.Timeout = timeout;
                        if (position > 0)
                        {
                            httpWebRequest.AddRange((int)position);
                        }
                        httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                        using (Stream stream = httpWebResponse.GetResponseStream())
                        {
                            stream.ReadTimeout = timeout;
                            long currentSize = position;
                            byte[] bytes = new byte[fileReadLength];
                            int readSize = stream.Read(bytes, 0, fileReadLength);
                            while (readSize > 0)
                            {
                                fileStream.Write(bytes, 0, readSize);
                                currentSize += readSize;
                                if (currentSize == downloadData.size)
                                {
                                    if (File.Exists(downloadData.path))
                                    {
                                        File.Delete(downloadData.path);
                                    }
                                    File.Move(tempPath, downloadData.path);
                                }
                                this.currentSize = currentSize;
                                readSize = stream.Read(bytes, 0, fileReadLength);
                            }
                        }
                    }
                    catch
                    {
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        state = DownloadState.Error;
                        error = "文件下载失败";
                    }
                    finally
                    {
                        if (httpWebRequest != null)
                        {
                            httpWebRequest.Abort();
                            httpWebRequest = null;
                        }
                        if (httpWebResponse != null)
                        {
                            httpWebResponse.Dispose();
                            httpWebResponse = null;
                        }
                    }
                }
            }
            if (state == DownloadState.Error)
            {
                return false;
            }
            return true;
        }

19 View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344

public byte[] GetBytes()
        {
            _stream.Position = 0L;
            var array = new byte[_stream.Length];
            var num = _stream.Read(array, 0, array.Length);
            if (num > 0)
            {
                return array;
            }

            return null;
        }

19 View Source File : CodedInputStream.cs
License : MIT License
Project Creator : 404Lcc

private bool RefillBuffer(bool mustSucceed)
        {
            if (bufferPos < bufferSize)
            {
                throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty.");
            }

            if (totalBytesRetired + bufferSize == currentLimit)
            {
                // Oops, we hit a limit.
                if (mustSucceed)
                {
                    throw InvalidProtocolBufferException.TruncatedMessage();
                }
                else
                {
                    return false;
                }
            }

            totalBytesRetired += bufferSize;

            bufferPos = 0;
            bufferSize = (input == null) ? 0 : input.Read(buffer, 0, buffer.Length);
            if (bufferSize < 0)
            {
                throw new InvalidOperationException("Stream.Read returned a negative count");
            }
            if (bufferSize == 0)
            {
                if (mustSucceed)
                {
                    throw InvalidProtocolBufferException.TruncatedMessage();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                RecomputeBufferSizeAfterLimit();
                int totalBytesRead =
                    totalBytesRetired + bufferSize + bufferSizeAfterLimit;
                if (totalBytesRead > sizeLimit || totalBytesRead < 0)
                {
                    throw InvalidProtocolBufferException.SizeLimitExceeded();
                }
                return true;
            }
        }

19 View Source File : CodedInputStream.cs
License : MIT License
Project Creator : 404Lcc

internal byte[] ReadRawBytes(int size)
        {
            if (size < 0)
            {
                throw InvalidProtocolBufferException.NegativeSize();
            }

            if (totalBytesRetired + bufferPos + size > currentLimit)
            {
                // Read to the end of the stream (up to the current limit) anyway.
                SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
                // Then fail.
                throw InvalidProtocolBufferException.TruncatedMessage();
            }

            if (size <= bufferSize - bufferPos)
            {
                // We have all the bytes we need already.
                byte[] bytes = new byte[size];
                ByteArray.Copy(buffer, bufferPos, bytes, 0, size);
                bufferPos += size;
                return bytes;
            }
            else if (size < buffer.Length)
            {
                // Reading more bytes than are in the buffer, but not an excessive number
                // of bytes.  We can safely allocate the resulting array ahead of time.

                // First copy what we have.
                byte[] bytes = new byte[size];
                int pos = bufferSize - bufferPos;
                ByteArray.Copy(buffer, bufferPos, bytes, 0, pos);
                bufferPos = bufferSize;

                // We want to use RefillBuffer() and then copy from the buffer into our
                // byte array rather than reading directly into our byte array because
                // the input may be unbuffered.
                RefillBuffer(true);

                while (size - pos > bufferSize)
                {
                    Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize);
                    pos += bufferSize;
                    bufferPos = bufferSize;
                    RefillBuffer(true);
                }

                ByteArray.Copy(buffer, 0, bytes, pos, size - pos);
                bufferPos = size - pos;

                return bytes;
            }
            else
            {
                // The size is very large.  For security reasons, we can't allocate the
                // entire byte array yet.  The size comes directly from the input, so a
                // maliciously-crafted message could provide a bogus very large size in
                // order to trick the app into allocating a lot of memory.  We avoid this
                // by allocating and reading only a small chunk at a time, so that the
                // malicious message must actually *be* extremely large to cause
                // problems.  Meanwhile, we limit the allowed size of a message elsewhere.

                // Remember the buffer markers since we'll have to copy the bytes out of
                // it later.
                int originalBufferPos = bufferPos;
                int originalBufferSize = bufferSize;

                // Mark the current buffer consumed.
                totalBytesRetired += bufferSize;
                bufferPos = 0;
                bufferSize = 0;

                // Read all the rest of the bytes we need.
                int sizeLeft = size - (originalBufferSize - originalBufferPos);
                List<byte[]> chunks = new List<byte[]>();

                while (sizeLeft > 0)
                {
                    byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)];
                    int pos = 0;
                    while (pos < chunk.Length)
                    {
                        int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos);
                        if (n <= 0)
                        {
                            throw InvalidProtocolBufferException.TruncatedMessage();
                        }
                        totalBytesRetired += n;
                        pos += n;
                    }
                    sizeLeft -= chunk.Length;
                    chunks.Add(chunk);
                }

                // OK, got everything.  Now concatenate it all into one buffer.
                byte[] bytes = new byte[size];

                // Start by copying the leftover bytes from this.buffer.
                int newPos = originalBufferSize - originalBufferPos;
                ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos);

                // And now all the chunks.
                foreach (byte[] chunk in chunks)
                {
                    Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
                    newPos += chunk.Length;
                }

                // Done.
                return bytes;
            }
        }

19 View Source File : ProtoWriter.cs
License : MIT License
Project Creator : 404Lcc

private static void CopyRawFromStream(Stream source, ProtoWriter writer)
        {
            byte[] buffer = writer.ioBuffer;
            int space = buffer.Length - writer.ioIndex, bytesRead = 1; // 1 here to spoof case where already full
            
            // try filling the buffer first   
            while (space > 0 && (bytesRead = source.Read(buffer, writer.ioIndex, space)) > 0)
            {
                writer.ioIndex += bytesRead;
                writer.position64 += bytesRead;
                space -= bytesRead;                
            }
            if (bytesRead <= 0) return; // all done using just the buffer; stream exhausted

            // at this point the stream still has data, but buffer is full; 
            if (writer.flushLock == 0)
            {
                // flush the buffer and write to the underlying stream instead
                Flush(writer);
                while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    writer.dest.Write(buffer, 0, bytesRead);
                    writer.position64 += bytesRead;
                }
            }
            else
            {
                do
                {
                    // need more space; resize (double) as necessary,
                    // requesting a reasonable minimum chunk each time
                    // (128 is the minimum; there may actually be much
                    // more space than this in the buffer)
                    DemandSpace(128, writer);
                    if((bytesRead = source.Read(writer.ioBuffer, writer.ioIndex,
                        writer.ioBuffer.Length - writer.ioIndex)) <= 0) break;
                    writer.position64 += bytesRead;
                    writer.ioIndex += bytesRead;
                } while (true);
            }

        }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public void StartDownload()
                {
                    try
                    {
                        HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(m_HttpDownloadInfo.Url);

                        if (0L < m_Position)
                        {
                            httpWebRequest.AddRange((int)m_Position);
                        }

                        WebResponse webResponse = httpWebRequest.GetResponse();
                        Stream webResponseStream = webResponse.GetResponseStream();

                        float progress = 0f;
                        long currentSize = m_Position;
                        long totalSize = m_Position + webResponse.ContentLength;

                        byte[] btContent = new byte[m_HttpDownloadInfo.DownloadBufferUnit];
                        int readSize = 0;
                        while (!m_Hreplacedtop && 0 < (readSize = webResponseStream.Read(btContent, 0, m_HttpDownloadInfo.DownloadBufferUnit)))
                        {
                            progress = (float)(currentSize += readSize) / totalSize;
                            if (null != OnDownloadProgress)
                            {
                                OnDownloadProgress.Invoke(this, new HttpDownloaderProgressEventArgs(progress));
                            }
                            m_FileStream.Flush();
                            m_FileStream.Write(btContent, 0, readSize);

                            System.Threading.Thread.Sleep(10);

                        }
                        m_FileStream.Close();
                        webResponseStream.Close();

                        if (!m_Hreplacedtop)
                        {
                            ReNameTempFile();

                            if (null != OnDownloadSuccess)
                            {
                                OnDownloadSuccess.Invoke(this, EventArgs.Empty);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != OnDownloadFailure)
                        {
                            OnDownloadFailure.Invoke(this,new HttpDownloaderFailureEventArgs(ex));
                        }
                        throw ex;
                    }
                }

19 View Source File : InBuffer.cs
License : MIT License
Project Creator : 91Act

public bool ReadBlock()
		{
			if (m_StreamWasExhausted)
				return false;
			m_ProcessedSize += m_Pos;
			int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize);
			m_Pos = 0;
			m_Limit = (uint)aNumProcessedBytes;
			m_StreamWasExhausted = (aNumProcessedBytes == 0);
			return (!m_StreamWasExhausted);
		}

19 View Source File : Lz4DecoderStream.cs
License : MIT License
Project Creator : 91Act

private int ReadByteCore()
        {
            var buf = decodeBuffer;

            if (inBufPos == inBufEnd)
            {
                int nRead = input.Read(buf, DecBufLen,
                    InBufLen < inputLength ? InBufLen : (int)inputLength);

#if CHECK_EOF
                if (nRead == 0)
                    return -1;
#endif

                inputLength -= nRead;

                inBufPos = DecBufLen;
                inBufEnd = DecBufLen + nRead;
            }

            return buf[inBufPos++];
        }

19 View Source File : Lz4DecoderStream.cs
License : MIT License
Project Creator : 91Act

private int ReadOffsetCore()
        {
            var buf = decodeBuffer;

            if (inBufPos == inBufEnd)
            {
                int nRead = input.Read(buf, DecBufLen,
                    InBufLen < inputLength ? InBufLen : (int)inputLength);

#if CHECK_EOF
                if (nRead == 0)
                    return -1;
#endif

                inputLength -= nRead;

                inBufPos = DecBufLen;
                inBufEnd = DecBufLen + nRead;
            }

            if (inBufEnd - inBufPos == 1)
            {
                buf[DecBufLen] = buf[inBufPos];

                int nRead = input.Read(buf, DecBufLen + 1,
                    InBufLen - 1 < inputLength ? InBufLen - 1 : (int)inputLength);

#if CHECK_EOF
                if (nRead == 0)
                {
                    inBufPos = DecBufLen;
                    inBufEnd = DecBufLen + 1;

                    return -1;
                }
#endif

                inputLength -= nRead;

                inBufPos = DecBufLen;
                inBufEnd = DecBufLen + nRead + 1;
            }

            int ret = (buf[inBufPos + 1] << 8) | buf[inBufPos];
            inBufPos += 2;

            return ret;
        }

19 View Source File : Lz4DecoderStream.cs
License : MIT License
Project Creator : 91Act

private int ReadCore(byte[] buffer, int offset, int count)
        {
            int nToRead = count;

            var buf = decodeBuffer;
            int inBufLen = inBufEnd - inBufPos;

            int fromBuf = nToRead < inBufLen ? nToRead : inBufLen;
            if (fromBuf != 0)
            {
                var bufPos = inBufPos;

                for (int c = fromBuf; c-- != 0;)
                    buffer[offset++] = buf[bufPos++];

                inBufPos = bufPos;
                nToRead -= fromBuf;
            }

            if (nToRead != 0)
            {
                int nRead;

                if (nToRead >= InBufLen)
                {
                    nRead = input.Read(buffer, offset,
                        nToRead < inputLength ? nToRead : (int)inputLength);
                    nToRead -= nRead;
                }
                else
                {
                    nRead = input.Read(buf, DecBufLen,
                        InBufLen < inputLength ? InBufLen : (int)inputLength);

                    inBufPos = DecBufLen;
                    inBufEnd = DecBufLen + nRead;

                    fromBuf = nToRead < nRead ? nToRead : nRead;

                    var bufPos = inBufPos;

                    for (int c = fromBuf; c-- != 0;)
                        buffer[offset++] = buf[bufPos++];

                    inBufPos = bufPos;
                    nToRead -= fromBuf;
                }

                inputLength -= nRead;
            }

            return count - nToRead;
        }

19 View Source File : LzInWindow.cs
License : MIT License
Project Creator : 91Act

public virtual void ReadBlock()
		{
			if (_streamEndWasReached)
				return;
			while (true)
			{
				int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos);
				if (size == 0)
					return;
				int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size);
				if (numReadBytes == 0)
				{
					_posLimit = _streamPos;
					UInt32 pointerToPostion = _bufferOffset + _posLimit;
					if (pointerToPostion > _pointerToLastSafePosition)
						_posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset);

					_streamEndWasReached = true;
					return;
				}
				_streamPos += (UInt32)numReadBytes;
				if (_streamPos >= _pos + _keepSizeAfter)
					_posLimit = _streamPos - _keepSizeAfter;
			}
		}

19 View Source File : LzOutWindow.cs
License : MIT License
Project Creator : 91Act

public bool Train(System.IO.Stream stream)
		{
			long len = stream.Length;
			uint size = (len < _windowSize) ? (uint)len : _windowSize;
			TrainSize = size;
			stream.Position = len - size;
			_streamPos = _pos = 0;
			while (size > 0)
			{
				uint curSize = _windowSize - _pos;
				if (size < curSize)
					curSize = size;
				int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize);
				if (numReadBytes == 0)
					return false;
				size -= (uint)numReadBytes;
				_pos += (uint)numReadBytes;
				_streamPos += (uint)numReadBytes;
				if (_pos == _windowSize)
					_streamPos = _pos = 0;
			}
			return true;
		}

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static AudioClip GetAudioClip(string name)
		{
			string[] wavNames = replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();

			foreach(var wav in wavNames)
            {
				Stream stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(wav);
				var split = wav.Split('.');
				string intername = split[split.Length - 2];
				if(intername == name)
                {
					byte[] buf = new byte[stream.Length];
					stream.Read(buf, 0, buf.Length);
					return WavUtility.ToAudioClip(buf, 0, intername);
				}
            }
			return null;
		}

19 View Source File : ObjectManager.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void Load()
            {
                if (loaded)
                    return;

                string[] resourceNames = replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
                foreach (string res in resourceNames)
                {
                    Logger.LogDebug($"Find Embeded Resource:{res}");
                    if (res.EndsWith(".png"))
                    {
                        try
                        {
                            Stream imageStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(res);
                            byte[] buffer = new byte[imageStream.Length];
                            imageStream.Read(buffer, 0, buffer.Length);
                            string[] split = res.Split('.');
                            string internalName = split[split.Length - 2];

                            if (res.Contains("images.objects"))
                            {
                                Texture2D tex = new Texture2D(1, 1);
                                tex.LoadImage(buffer.ToArray());
                                images.Add(internalName, tex);
                            }
                            else
                            {
                                raw_images.Add(internalName, buffer);
                            }
                        }
                        catch
                        {
                            loaded = false;
                        }
                    }
                }
                loaded = true;
            }

19 View Source File : StreamHelper.cs
License : MIT License
Project Creator : a1q123456

public static byte[] ReadBytes(this Stream stream, int count)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            var result = new byte[count];
            var bytesRead = 0;
            while (count > 0)
            {
                var n = stream.Read(result, bytesRead, count);
                if (n == 0)
                    break;
                bytesRead += n;
                count -= n;
            }

            if (bytesRead != result.Length)
            {
                throw new EndOfStreamException();
            }

            return result;
        }

19 View Source File : UserLicense.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void ShowLicense()
        {
            if(!agreeLicense)
            {
                string bundleN = "userlicense";
                replacedetBundle ab = null;  // You probably want this to be defined somewhere more global.
                replacedembly asm = replacedembly.GetExecutingreplacedembly();
                foreach (string res in asm.GetManifestResourceNames()) 
                {
                    using (Stream s = asm.GetManifestResourceStream(res))
                    {
                        if (s == null) continue;
                        byte[] buffer = new byte[s.Length];
                        s.Read(buffer, 0, buffer.Length);
                        s.Dispose();
                        string bundleName = Path.GetExtension(res).Substring(1);
                        if (bundleName != bundleN) continue;
                        Logger.Log("Loading bundle " + bundleName);
                        ab = replacedetBundle.LoadFromMemory(buffer); // Store this somewhere you can access again.
                    }
                }
                var _canvas = ab.Loadreplacedet<GameObject>("userlicense");
                UnityEngine.Object.Instantiate(_canvas);
                Logger.Log("Show User License");
            }
        }

19 View Source File : Ecoji.cs
License : MIT License
Project Creator : abock

public static void Encode(Stream input, TextWriter output, int wrap = 0)
    {
        if (input is null)
            throw new ArgumentNullException(nameof(input));

        if (output is null)
            throw new ArgumentNullException(nameof(output));

        var wrapLineProgress = 0;

        var b = new byte[5];

        while (true)
        {
            var read = 0;
            while (read < b.Length)
            {
                var n = input.Read(b, read, b.Length - read);
                read += n;
                if (n == 0)
                    break;
            }

            if (read <= 0) {
                if (wrapLineProgress > 0)
                    output.WriteLine();
                break;
            }
            
            for (var i = read; i < b.Length; i++)
                b[i] = 0;

            output.WriteRune(emojis[b[0] << 2 | b[1] >> 6]);

            switch (read)
            {
                case 1:
                    output.WriteRune(padding);
                    output.WriteRune(padding);
                    output.WriteRune(padding);
                    break;
                case 2:
                    output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
                    output.WriteRune(padding);
                    output.WriteRune(padding);
                    break;
                case 3:
                    output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
                    output.WriteRune(emojis[(b[2] & 0x0f) << 6 | b[3] >> 2]);
                    output.WriteRune(padding);
                    break;
                case 4:
                    output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
                    output.WriteRune(emojis[(b[2] & 0x0f) << 6 | b[3] >> 2]);

                    var pad4 = (b[3] & 0x03) switch
                    {
                        0 => padding40,
                        1 => padding41,
                        2 => padding42,
                        3 => padding43,
                        _ => 0
                    };

                    if (pad4 > 0)
                        output.WriteRune(pad4);
                    break;
                case 5:
                    output.WriteRune(emojis[(b[1] & 0x3f) << 4 | b[2] >> 4]);
                    output.WriteRune(emojis[(b[2] & 0x0f) << 6 | b[3] >> 2]);
                    output.WriteRune(emojis[(b[3] & 0x03) << 8 | b[4]]);
                    break;
            }

            if (wrap > 0)
            {
                wrapLineProgress += 4;
                if (wrapLineProgress >= wrap)
                {
                    output.WriteLine();
                    wrapLineProgress = 0;
                }
            }
        }

19 View Source File : Host.cs
License : MIT License
Project Creator : acandylevey

private JObject Read()
        {
            Log.LogMessage("Waiting for Data");

            Stream stdin = Console.OpenStandardInput();

            byte[] lengthBytes = new byte[4];
            stdin.Read(lengthBytes, 0, 4);

            char[] buffer = new char[BitConverter.ToInt32(lengthBytes, 0)];

            using (StreamReader reader = new StreamReader(stdin))
                if (reader.Peek() >= 0)
                    reader.Read(buffer, 0, buffer.Length);

            return JsonConvert.DeserializeObject<JObject>(new string(buffer));
        }

19 View Source File : FileCacheManager.cs
License : Apache License 2.0
Project Creator : acarteas

public virtual long WriteFile(FileCache.PayloadMode mode, string key, FileCachePayload data, string regionName = null, bool policyUpdateOnly = false)
        {
            string cachedPolicy = GetPolicyPath(key, regionName);
            string cachedItemPath = GetCachePath(key, regionName);
            long cacheSizeDelta = 0;

            //ensure that the cache policy contains the correct key
            data.Policy.Key = key;

            if (!policyUpdateOnly)
            {
                long oldBlobSize = 0;
                if (File.Exists(cachedItemPath))
                {
                    oldBlobSize = new FileInfo(cachedItemPath).Length;
                }

                switch (mode)
                {
                    case FileCache.PayloadMode.Serializable:
                        using (FileStream stream = GetStream(cachedItemPath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            formatter.Serialize(stream, data.Payload);
                        }
                        break;
                    case FileCache.PayloadMode.RawBytes:
                        using (FileStream stream = GetStream(cachedItemPath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            using (BinaryWriter writer = new BinaryWriter(stream))
                            {
                                if (data.Payload is byte[])
                                {
                                    byte[] dataPayload = (byte[])data.Payload;
                                    writer.Write(dataPayload);
                                }
                                else if (data.Payload is Stream)
                                {
                                    Stream dataPayload = (Stream)data.Payload;
                                    byte[] bytePayload = new byte[dataPayload.Length - dataPayload.Position];
                                    dataPayload.Read(bytePayload, (int)dataPayload.Position, bytePayload.Length);
                                    // no close or the like for data.Payload - we are not the owner
                                }
                            }
                        }
                        break;

                    case FileCache.PayloadMode.Filename:
                        File.Copy((string)data.Payload, cachedItemPath, true);
                        break;
                }

                //adjust cache size (while we have the file to ourselves)
                cacheSizeDelta += new FileInfo(cachedItemPath).Length - oldBlobSize;
            }

            //remove current policy file from cache size calculations
            if (File.Exists(cachedPolicy))
            {
                cacheSizeDelta -= new FileInfo(cachedPolicy).Length;
            }

            //write the cache policy
            using (FileStream stream = GetStream(cachedPolicy, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    data.Policy.Serialize(writer);
                }
            }

            // Adjust cache size outside of the using blocks to ensure it's after the data is written.
            cacheSizeDelta += new FileInfo(cachedPolicy).Length;

            return cacheSizeDelta;
        }

19 View Source File : PrimitiveMethods.Download.cs
License : MIT License
Project Creator : Accelerider

public static IObservable<(long Offset, int Bytes)> CreateBlockDownloadItem(
            Func<Task<(HttpWebResponse response, Stream inputStream)>> streamPairFactory,
            BlockTransferContext context) => Observable.Create<(long Offset, int Bytes)>(o =>
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            // Execute copy stream by async.
            Task.Run(async () =>
            {
                try
                {
                    (HttpWebResponse response, Stream outputStream) = await streamPairFactory();

                    using (response)
                    using (var inputStream = response.GetResponseStream())
                    using (outputStream)
                    {
                        byte[] buffer = new byte[128 * 1024];
                        int count;

                        Guards.ThrowIfNull(inputStream);

                        // ReSharper disable once PossibleNullReferenceException
                        while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                Debug.WriteLine($"[CANCELLED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                                o.OnError(new BlockTransferException(context, new OperationCanceledException()));
                                return;
                            }

                            outputStream.Write(buffer, 0, count);
                            o.OnNext((context.Offset, count));
                        }
                    }

                    o.OnCompleted();
                }
                catch (Exception e)
                {
                    o.OnError(new BlockTransferException(context, e));
                }
            }, cancellationToken);

            return () =>
            {
                Debug.WriteLine($"[DISPOSED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                cancellationTokenSource.Cancel();
            };
        });

19 View Source File : PacketHeaderOptional.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void Unpack(BinaryReader reader, PacketHeader header)
        {
            Header = header;
            Size = (uint)reader.BaseStream.Position;
            BinaryWriter writer = new BinaryWriter(headerBytes);

            if (header.HasFlag(PacketHeaderFlags.ServerSwitch)) // 0x100
            {
                writer.Write(reader.ReadBytes(8));
            }

            if (header.HasFlag(PacketHeaderFlags.RequestRetransmit)) // 0x1000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                uint retransmitCount = reader.ReadUInt32();
                writer.Write(retransmitCount);
                RetransmitData = new List<uint>();
                for (uint i = 0u; i < retransmitCount; i++)
                {
                    if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                    uint sequence = reader.ReadUInt32();
                    writer.Write(sequence);
                    RetransmitData.Add(sequence);
                }
            }

            if (header.HasFlag(PacketHeaderFlags.RejectRetransmit)) // 0x2000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                uint count = reader.ReadUInt32();
                writer.Write(count);
                for (int i = 0; i < count; i++)
                {
                    if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                    writer.Write(reader.ReadBytes(4));
                }
            }

            if (header.HasFlag(PacketHeaderFlags.AckSequence)) // 0x4000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                AckSequence = reader.ReadUInt32();
                writer.Write(AckSequence);
            }

            if (header.HasFlag(PacketHeaderFlags.LoginRequest)) // 0x10000
            {
                long position = reader.BaseStream.Position;
                long length = reader.BaseStream.Length - position;
                if (length < 1) { IsValid = false; return; }
                byte[] loginBytes = new byte[length];
                reader.BaseStream.Read(loginBytes, (int)position, (int)length);
                writer.Write(loginBytes);
                reader.BaseStream.Position = position;
            }

            if (header.HasFlag(PacketHeaderFlags.WorldLoginRequest)) // 0x20000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                long position = reader.BaseStream.Position;
                writer.Write(reader.ReadBytes(8));
                reader.BaseStream.Position = position;
            }

            if (header.HasFlag(PacketHeaderFlags.ConnectResponse)) // 0x80000
            {
                long position = reader.BaseStream.Position;
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                writer.Write(reader.ReadBytes(8));
                reader.BaseStream.Position = position;
            }

            if (header.HasFlag(PacketHeaderFlags.CICMDCommand)) // 0x400000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                writer.Write(reader.ReadBytes(8));
            }

            if (header.HasFlag(PacketHeaderFlags.TimeSync)) // 0x1000000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                TimeSynch = reader.ReadDouble();
                writer.Write(TimeSynch);
            }

            if (header.HasFlag(PacketHeaderFlags.Ecreplacedquest)) // 0x2000000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                EcreplacedquestClientTime = reader.ReadSingle();
                writer.Write(EcreplacedquestClientTime);
            }

            if (header.HasFlag(PacketHeaderFlags.Flow)) // 0x8000000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 6) { IsValid = false; return; }
                FlowBytes = reader.ReadUInt32();
                FlowInterval = reader.ReadUInt16();
                writer.Write(FlowBytes);
                writer.Write(FlowInterval);
            }

            Size = (uint)reader.BaseStream.Position - Size;
        }

19 View Source File : StreamParser.cs
License : MIT License
Project Creator : actions

public override int Read(byte[] buffer, int offset, int count)
        {
            // check that the read is only in our substream
            count = EnsureLessThanOrEqualToRemainingBytes(count);

            return m_stream.Read(buffer, offset, count);
        }

See More Examples