System.IO.Stream.ReadByte()

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

1333 Examples 7

19 View Source File : BoolMarshaler.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static bool Demarshal(Stream stream)
        {
            int buffer = stream.ReadByte();
            return buffer != 0;
        }

19 View Source File : Hash.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static short ReadShort(Stream stream)
            {
                return (short)(stream.ReadByte() + (stream.ReadByte() << 8));
            }

19 View Source File : TweakableStream.cs
License : MIT License
Project Creator : airbreather

public override int ReadByte() => _inner.ReadByte();

19 View Source File : BinaryDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

private uint Footprint(Stream File, int iPos, ref int iLastPos, uint uiLastHash)
        {
            uint uiHash = 0;

            unchecked //We must allow rollovers
            {
                if (iPos == iLastPos + 1)
                {
                    //Rehash using a Karp-Rabin rehashing scheme.
                    File.Seek(iLastPos, SeekOrigin.Begin);
                    int iPrevByte = File.ReadByte();
                    File.Seek(iPos + m_iFootprintLength - 1, SeekOrigin.Begin);
                    int iNextByte = File.ReadByte();
                    return (uint)(((uiLastHash - iPrevByte * m_uiDPower) << 1) + iNextByte);
                }
                else
                {
                    //Generate a new hash
                    File.Seek(iPos, SeekOrigin.Begin);
                    for (int i = 0; i < m_iFootprintLength; i++)
                    {
                        uiHash = (uint)((uiHash << 1) + File.ReadByte());
                    }
                }
            }

            iLastPos = iPos;

            return uiHash;
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void WriteBit(Bit data)
        {
            stream.Seek(offset, SeekOrigin.Begin);
            byte value = (byte)stream.ReadByte();
            stream.Seek(offset, SeekOrigin.Begin);
            if (!MSB)
            {
                value &= (byte)~(1 << bit);
                value |= (byte)(data << bit);
            }
            else
            {
                value &= (byte)~(1 << (7 - bit));
                value |= (byte)(data << (7 - bit));
            }
            if (ValidPosition)
            {
                stream.WriteByte(value);
            }
            else
            {
                if (AutoIncreaseStream)
                {
                    if (ChangeLength(Length + (offset - Length) + 1))
                    {
                        stream.WriteByte(value);
                    }
                    else
                    {
                        throw new IOException("Cannot write in an offset bigger than the length of the stream");
                    }
                }
                else
                {
                    throw new IOException("Cannot write in an offset bigger than the length of the stream");
                }
            }
            AdvanceBit();
            stream.Seek(offset, SeekOrigin.Begin);
        }

19 View Source File : RedisReader.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

string ReadLine()
        {
            StringBuilder sb = new StringBuilder();
            char c;
            bool should_break = false;
            while (true)
            {
                 c = (char)_stream.ReadByte();
                if (c == '\r') // TODO: remove hardcoded
                    should_break = true;
                else if (c == '\n' && should_break)
                    break;
                else
                {
                    sb.Append(c);
                    should_break = false;
                }
            }
			//Console.WriteLine($"ReadLine: {sb.ToString()}");
			return sb.ToString();
        }

19 View Source File : ClippedStream.cs
License : GNU General Public License v3.0
Project Creator : anotak

public override int ReadByte()
		{
			// Check if this exceeds limits
			if((this.position + 1) > (this.length + 1))
				throw new ArgumentException("Attempted to read outside the range of the stream.");

			// Seek if needed
			if(basestream.Position != (this.offset + this.position))
				basestream.Seek(this.offset + this.position, SeekOrigin.Begin);

			// Read from base stream
			position++;
			return basestream.ReadByte();
		}

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

public void Normalize()
		{
			while (Range < kTopValue)
			{
				Code = (Code << 8) | (byte)Stream.ReadByte();
				Range <<= 8;
			}
		}

19 View Source File : Hash.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static uint ReadUInt(Stream stream)
            {
                return (uint)(stream.ReadByte()
                    + (stream.ReadByte() << 8)
                    + (stream.ReadByte() << 16)
                    + (stream.ReadByte() << 24));
            }

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

public uint DecodeDirectBits(int numTotalBits)
		{
			uint range = Range;
			uint code = Code;
			uint result = 0;
			for (int i = numTotalBits; i > 0; i--)
			{
				range >>= 1;
				/*
				result <<= 1;
				if (code >= range)
				{
					code -= range;
					result |= 1;
				}
				*/
				uint t = (code - range) >> 31;
				code -= range & (t - 1);
				result = (result << 1) | (1 - t);

				if (range < kTopValue)
				{
					code = (code << 8) | (byte)Stream.ReadByte();
					range <<= 8;
				}
			}
			Range = range;
			Code = code;
			return result;
		}

19 View Source File : Interface.cs
License : MIT License
Project Creator : Aminator

public static ValueTask<Gltf> LoadModelAsync(Stream stream)
        {
            bool binaryFile = false;

            uint magic = 0;
            magic |= (uint)stream.ReadByte();
            magic |= (uint)stream.ReadByte() << 8;
            magic |= (uint)stream.ReadByte() << 16;
            magic |= (uint)stream.ReadByte() << 24;

            if (magic == GLTFHEADER) binaryFile = true;

            stream.Position = 0; // restart read position

            Stream fileData;

            if (binaryFile)
            {
                fileData = new MemoryStream(ParseBinary(stream));
            }
            else
            {
                fileData = stream;
            }

            return JsonSerializer.DeserializeAsync<Gltf>(fileData);
        }

19 View Source File : LMSensors.cs
License : MIT License
Project Creator : AlexGyver

private string ReadFirstLine(Stream stream) {
        StringBuilder sb = new StringBuilder();
        try {
          stream.Seek(0, SeekOrigin.Begin);
          int b = stream.ReadByte();
          while (b != -1 && b != 10) {
            sb.Append((char)b);
            b = stream.ReadByte();
          }
        } catch { }
        return sb.ToString();
      }

19 View Source File : RedisReader.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public RedisMessage ReadType()
        {
            RedisMessage type = (RedisMessage)_stream.ReadByte();
			//Console.WriteLine($"ReadType: {type}");
            if (type == RedisMessage.Error)
                throw new RedisException(ReadStatus(false));
            return type;
        }

19 View Source File : BinaryDiffLines.cs
License : Apache License 2.0
Project Creator : AmpScm

private string GetLineString(Stream S, int iLength)
        {
            //The magic number 3 appears in this method because each
            //byte takes two hex characters plus a space after it.

            StringBuilder sbHex = new StringBuilder(iLength * 3);
            StringBuilder sbChars = new StringBuilder(iLength);

            for (int i = 0; i < iLength; i++)
            {
                int iByte = S.ReadByte();
                if (iByte == -1)
                {
                    sbHex.Append("   ");
                }
                else
                {
                    byte by = (byte)iByte;
                    sbHex.AppendFormat("{0:X2} ", by);
                    char ch = (char)by;
                    sbChars.Append(char.IsControl(ch) ? '.' : ch);
                }
            }

            while (sbHex.Length < 3 * m_iBytesPerLine)
            {
                sbHex.Append("   ");
            }

            return string.Concat("    ", sbHex.ToString(), "   ", sbChars.ToString());
        }

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

internal static uint ReadRawVarint32(Stream input)
        {
            int result = 0;
            int offset = 0;
            for (; offset < 32; offset += 7)
            {
                int b = input.ReadByte();
                if (b == -1)
                {
                    throw InvalidProtocolBufferException.TruncatedMessage();
                }
                result |= (b & 0x7f) << offset;
                if ((b & 0x80) == 0)
                {
                    return (uint) result;
                }
            }
            // Keep reading up to 64 bits.
            for (; offset < 64; offset += 7)
            {
                int b = input.ReadByte();
                if (b == -1)
                {
                    throw InvalidProtocolBufferException.TruncatedMessage();
                }
                if ((b & 0x80) == 0)
                {
                    return (uint) result;
                }
            }
            throw InvalidProtocolBufferException.MalformedVarint();
        }

19 View Source File : DataInputReader.cs
License : MIT License
Project Creator : angelobreuer

public byte ReadByte()
    {
        var b = BaseStream.ReadByte();

        if (b == -1)
        {
            throw new EndOfStreamException("Reached end of stream while reading single byte.");
        }

        return (byte)b;
    }

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

public virtual byte[] AppendAndSave(Stream newData, Stream originalData) {
            originalData.Seek(offset + 60, SeekOrigin.Begin);
            var OldChunkCompressedSizes = new byte[(entry_count - 1) * 4];
            originalData.Read(OldChunkCompressedSizes, 0, OldChunkCompressedSizes.Length);

            var lastCunkCompressedSize = originalData.ReadByte() | originalData.ReadByte() << 8 | originalData.ReadByte() << 16 | originalData.ReadByte() << 24; //ReadInt32

            var lastCunkDecompressedSize = uncompressed_size - (chunk_size * (entry_count - 1));

            uncompressed_size = (int)(size_decompressed += newData.Length);
            entry_count = uncompressed_size / chunk_size;
            if (uncompressed_size % chunk_size != 0) entry_count++;
            head_size = entry_count * 4 + 48;

            var msToSave = new MemoryStream();
            var bw = new BinaryWriter(msToSave);

            msToSave.Seek(60 + (entry_count * 4), SeekOrigin.Begin);
            var o = new byte[compressed_size - lastCunkCompressedSize];
            originalData.Read(o, 0, o.Length);
            bw.Write(o);

            var lastChunkCompressedData = new byte[lastCunkCompressedSize];
            originalData.Read(lastChunkCompressedData, 0, lastCunkCompressedSize);
            var lastCunkDecompressedData = new byte[lastCunkDecompressedSize + 64];
			_ = OodleLZ_Decompress(lastChunkCompressedData, lastCunkCompressedSize, lastCunkDecompressedData, lastCunkDecompressedSize, 0, 0, 0, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, 3);

            newData.Seek(0, SeekOrigin.Begin);
            compressed_size -= lastCunkCompressedSize;
            var NewChunkCompressedSizes = new int[entry_count - (OldChunkCompressedSizes.Length / 4)];

            var FirstNewDataChunk = new byte[Math.Min(chunk_size - lastCunkDecompressedSize, newData.Length)];
            newData.Read(FirstNewDataChunk, 0, FirstNewDataChunk.Length);
            FirstNewDataChunk = lastCunkDecompressedData.Take(lastCunkDecompressedSize).Concat(FirstNewDataChunk).ToArray();
            var CompressedChunk = new byte[FirstNewDataChunk.Length + 548];
            var CompressedLength = OodleLZ_Compress(encoder, FirstNewDataChunk, FirstNewDataChunk.Length, CompressedChunk, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
            compressed_size += NewChunkCompressedSizes[0] = CompressedLength;
            bw.Write(CompressedChunk, 0, CompressedLength);
            for (var i = 1; i < NewChunkCompressedSizes.Length; i++) {
                var size = (i + 1 == NewChunkCompressedSizes.Length) ? uncompressed_size - (chunk_size * (entry_count - 1)) : chunk_size;
                var b = new byte[size];
                newData.Read(b, 0, size);
                var by = new byte[b.Length + 548];
                var l = OodleLZ_Compress(encoder, b, size, by, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
                compressed_size += NewChunkCompressedSizes[i] = l;
                bw.Write(by, 0, l);
            }
            size_compressed = compressed_size;

            msToSave.Seek(60, SeekOrigin.Begin);
            bw.Write(OldChunkCompressedSizes);
            for (var i = 0; i < NewChunkCompressedSizes.Length; i++)
                bw.Write(NewChunkCompressedSizes[i]);

            msToSave.Seek(0, SeekOrigin.Begin);
            bw.Write(uncompressed_size);
            bw.Write(compressed_size);
            bw.Write(head_size);
            bw.Write((uint)encoder);
            bw.Write(unknown);
            bw.Write(size_decompressed);
            bw.Write(size_compressed);
            bw.Write(entry_count);
            bw.Write(chunk_size);
            bw.Write(unknown3);
            bw.Write(unknown4);
            bw.Write(unknown5);
            bw.Write(unknown6);

            bw.Flush();
            var result = msToSave.ToArray();
            bw.Close();
            return result;
        }

19 View Source File : BinarySerializer.cs
License : MIT License
Project Creator : ansel86castro

private object ReadCodedMap(Stream stream, Types typeCode, Type? type)
        {                    
            int count = 0;
            switch (typeCode)
            {
                case Types.TYPE_CODED_MAP_8: count = stream.ReadByte(); break;
                case Types.TYPE_CODED_MAP_16: count = ReadNumber<ushort>(stream); break;
                case Types.TYPE_CODED_MAP_32: count = ReadNumber<int>(stream); break;
            }

            if (type == null)
            {
                return ReadMap(stream, count, null);
            }

            var item = (IReflectorMetadataProvider)Activator.CreateInstance(type);
            IReflectorMetadata accesor = item.GetAccesor();

            for (int i = 0; i < count; i++)
            {
                int code = 0;
                var keyCode = (Types)stream.ReadByte();
                switch (keyCode)
                {
                    case Types.TYPE_INT_8: code = stream.ReadByte(); break;
                    case Types.TYPE_UINT_8: code = stream.ReadByte(); break;
                    case Types.TYPE_INT_16: code = ReadNumber<short>(stream); break;
                    case Types.TYPE_UINT_16: code = ReadNumber<ushort>(stream); break;
                    case Types.TYPE_INT_32: code = ReadNumber<int>(stream); break;
                }

                var propertyType = accesor.GetPropertyType(code);
                var value = Deserialize(stream, propertyType);
                accesor.SetValue(item, code, value);
            }

            return item;
        }

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

public static long TryReadUInt32BigEndian(this Stream stream)
        {
            int byte1 = stream.ReadByte();
            if (byte1 == -1)
            {
                return -1;
            }

            int byte2 = stream.ReadByte();
            if (byte2 == -1)
            {
                return -1;
            }

            int byte3 = stream.ReadByte();
            if (byte3 == -1)
            {
                return -1;
            }

            int byte4 = stream.ReadByte();
            if (byte4 == -1)
            {
                return -1;
            }

            return (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4;
        }

19 View Source File : Hash.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static int ReadInt(Stream stream)
            {
                return stream.ReadByte()
                    + (stream.ReadByte() << 8)
                    + (stream.ReadByte() << 16)
                    + (stream.ReadByte() << 24);
            }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public Bit ReadBit()
        {
            if (!ValidPosition)
            {
                throw new IOException("Cannot read in an offset bigger than the length of the stream");
            }
            stream.Seek(offset, SeekOrigin.Begin);
            byte value;
            if (!MSB)
            {
                value = (byte)((stream.ReadByte() >> (bit)) & 1);
            }
            else
            {
                value = (byte)((stream.ReadByte() >> (7 - bit)) & 1);
            }
            AdvanceBit();
            stream.Seek(offset, SeekOrigin.Begin);
            return value;
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void bitwiseShift(int bits, bool leftShift)
        {
            if (!ValidPositionWhen(8))
            {
                throw new IOException("Cannot read in an offset bigger than the length of the stream");
            }
            Seek(offset, 0);
            if (bits != 0 && bits <= 7)
            {
                byte value = (byte)stream.ReadByte();
                if (leftShift)
                {
                    value = (byte)(value << bits);
                }
                else
                {
                    value = (byte)(value >> bits);
                }
                Seek(offset, 0);
                stream.WriteByte(value);
            }
            bit = 0;
            offset++;
        }

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

private static byte ReadStreamByte(Stream stream)
            {
                int one = stream.ReadByte();
                if (one == -1)
                {
                    throw new Exception();//end
                }

                return (byte)one;
            }

19 View Source File : AMD10CPU.cs
License : MIT License
Project Creator : AlexGyver

private string ReadFirstLine(Stream stream) {
      StringBuilder sb = new StringBuilder();
      try {
        stream.Seek(0, SeekOrigin.Begin);
        int b = stream.ReadByte();
        while (b != -1 && b != 10) {
          sb.Append((char)b);
          b = stream.ReadByte();
        }
      } catch { }
      return sb.ToString();
    }

19 View Source File : FileReader.cs
License : MIT License
Project Creator : Abdesol

public static StreamReader OpenStream(Stream stream, Encoding defaultEncoding)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");
			if (stream.Position != 0)
				throw new ArgumentException("stream is not positioned at beginning.", "stream");
			if (defaultEncoding == null)
				throw new ArgumentNullException("defaultEncoding");

			if (stream.Length >= 2) {
				// the autodetection of StreamReader is not capable of detecting the difference
				// between ISO-8859-1 and UTF-8 without BOM.
				int firstByte = stream.ReadByte();
				int secondByte = stream.ReadByte();
				switch ((firstByte << 8) | secondByte) {
					case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader
					case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE)
					case 0xfeff: // UTF-16 BE BOM
					case 0xefbb: // start of UTF-8 BOM
						// StreamReader autodetection works
						stream.Position = 0;
						return new StreamReader(stream);
					default:
						return AutoDetect(stream, (byte)firstByte, (byte)secondByte, defaultEncoding);
				}
			} else {
				if (defaultEncoding != null) {
					return new StreamReader(stream, defaultEncoding);
				} else {
					return new StreamReader(stream);
				}
			}
		}

19 View Source File : MemoryUtil.cs
License : GNU General Public License v3.0
Project Creator : am0nsec

protected string ReadAscii(Int64 offset) {
            int length = 0;
            this.ModuleStream.Seek(offset, SeekOrigin.Begin);
            while (this.ModuleStream.ReadByte() != 0x00)
                length++;

            Span<byte> s = length <= 1024 ? stackalloc byte[length] : new byte[length];
            this.ModuleStream.Seek(offset, SeekOrigin.Begin);
            this.ModuleStream.Read(s);
            return Encoding.ASCII.GetString(s);
        }

19 View Source File : GifDecoder.cs
License : MIT License
Project Creator : AlexGyver

private int Read() 
		{
			int curByte = 0;
			try 
			{
				curByte = inStream.ReadByte();
			} 
			catch (IOException) 
			{
				status = StatusFormatError;
			}
			return curByte;
		}

19 View Source File : FsBufferedReaderWriter.cs
License : MIT License
Project Creator : Adoxio

protected void ReadHeader()
		{
			try
			{
				var fs = this.fileStream;

				// Check header
				byte[] fileMarker = new byte[this.headerMarker.Length];

				fs.Seek(0, SeekOrigin.Begin);
				fs.Read(fileMarker, 0, fileMarker.Length);

				if (!fileMarker.SequenceEqual(this.headerMarker))
				{
					throw new InvalidOperationException(
						string.Format("File {0} does not looks like search index",
						this.File.FullName));
				}

				// Read version
				var version = fs.ReadByte(); // Not in use right now. Just in case for required next changes

				this.lengthOffset = fs.Position;
				this.dataOffset = this.lengthOffset + sizeof(long);
			}
			catch (Exception e)
			{
				throw new InvalidOperationException("Not able to read keys from file", e);
			}
		}

19 View Source File : BinaryDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

private int ExtendMatch(Stream BaseFile, int iBasePos, Stream VerFile, int iVerPos)
        {
            BaseFile.Seek(iBasePos, SeekOrigin.Begin);
            VerFile.Seek(iVerPos, SeekOrigin.Begin);
            int iLength = 0;
            int iByte = 0;
            while ((iByte = BaseFile.ReadByte()) == VerFile.ReadByte() && iByte != -1) iLength++;
            return iLength;
        }

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

public int ReadByte()
        {
            lock (_streamLock)
                return Stream.ReadByte();
        }

19 View Source File : BinaryDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

private bool Verify(Stream BaseFile, int iBasePos, Stream VerFile, int iVerPos)
        {
            BaseFile.Seek(iBasePos, SeekOrigin.Begin);
            VerFile.Seek(iVerPos, SeekOrigin.Begin);
            return BaseFile.ReadByte() == VerFile.ReadByte();
        }

19 View Source File : RedisReader.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void ReadCRLF() // TODO: remove hardcoded
        {
            var r = _stream.ReadByte();
            var n = _stream.ReadByte();
			//Console.WriteLine($"ReadCRLF: {r} {n}");
			if (r != (byte)13 && n != (byte)10)
                throw new RedisProtocolException(String.Format("Expecting CRLF; got bytes: {0}, {1}", r, n));
        }

19 View Source File : ByteMarshaler.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static byte Demarshal(Stream stream)
        {
            return (byte) stream.ReadByte();
        }

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

public override int ReadByte()
        {
            VerifyNotDisposed();

            if ((this.Position + sizeof(byte)) > this.Length)
            {
                return -1;
            }

            return this.stream.ReadByte();
        }

19 View Source File : HttpBase.cs
License : MIT License
Project Creator : andruzzzhka

private static string[] readHeaders (Stream stream, int maxLength)
    {
      var buff = new List<byte> ();
      var cnt = 0;
      Action<int> add = i => {
        if (i == -1)
          throw new EndOfStreamException ("The header cannot be read from the data source.");

        buff.Add ((byte) i);
        cnt++;
      };

      var read = false;
      while (cnt < maxLength) {
        if (stream.ReadByte ().EqualsWith ('\r', add) &&
            stream.ReadByte ().EqualsWith ('\n', add) &&
            stream.ReadByte ().EqualsWith ('\r', add) &&
            stream.ReadByte ().EqualsWith ('\n', add)) {
          read = true;
          break;
        }
      }

      if (!read)
        throw new WebSocketException ("The length of header part is greater than the max length.");

      return Encoding.UTF8.GetString (buff.ToArray ())
             .Replace (CrLf + " ", " ")
             .Replace (CrLf + "\t", " ")
             .Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries);
    }

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Encoding GetEncoding(Stream stream, Encoding defaultEncoding)
        {
            var targetEncoding = defaultEncoding;
            if (stream == null || stream.Length < 2)
                return targetEncoding;
            //保存文件流的前4个字节
            byte byte3 = 0;
            //保存当前Seek位置
            var origPos = stream.Seek(0, SeekOrigin.Begin);
            stream.Seek(0, SeekOrigin.Begin);

            var nByte = stream.ReadByte();
            var byte1 = Convert.ToByte(nByte);
            var byte2 = Convert.ToByte(stream.ReadByte());
            if (stream.Length >= 3)
            {
                byte3 = Convert.ToByte(stream.ReadByte());
            }
            if (stream.Length >= 4)
            {
                // ReSharper disable ReturnValueOfPureMethodIsNotUsed
                Convert.ToByte(stream.ReadByte());
                // ReSharper restore ReturnValueOfPureMethodIsNotUsed
            }
            //根据文件流的前4个字节判断Encoding
            //Unicode {0xFF, 0xFE};
            //BE-Unicode {0xFE, 0xFF};
            //UTF8 = {0xEF, 0xBB, 0xBF};
            if (byte1 == 0xFE && byte2 == 0xFF) //UnicodeBe
            {
                targetEncoding = Encoding.BigEndianUnicode;
            }
            if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF) //Unicode
            {
                targetEncoding = Encoding.Unicode;
            }
            if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF) //UTF8
            {
                targetEncoding = Encoding.UTF8;
            }
            //恢复Seek位置       
            stream.Seek(origPos, SeekOrigin.Begin);
            return targetEncoding;
        }

19 View Source File : ImageDataFormat.cs
License : GNU General Public License v3.0
Project Creator : anotak

private static bool CheckSignature(Stream data, int[] sig)
		{
			int b;
			
			// Go for all bytes
			for(int i = 0; i < sig.Length; i++)
			{
				// When byte doesnt match the signature, leave
				b = data.ReadByte();
				if(b != sig[i]) return false;
			}

			// Signature matches
			return true;
		}

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

public void Init(System.IO.Stream stream)
		{
			// Stream.Init(stream);
			Stream = stream;

			Code = 0;
			Range = 0xFFFFFFFF;
			for (int i = 0; i < 5; i++)
				Code = (Code << 8) | (byte)Stream.ReadByte();
		}

19 View Source File : BinarySerializer.cs
License : MIT License
Project Creator : ansel86castro

public object? Deserialize(Stream stream, Type? type)
        {
            var typeByte = stream.ReadByte();
            if (typeByte == -1) return null;
            var typeCode = (Types)typeByte;

            object? value;
            switch (typeCode)
            {
                case Types.TYPE_NONE: return null;
                case Types.TYPE_TRUE: value = true; break;
                case Types.TYPE_FALSE: value = false; break;
                case Types.TYPE_INT_8: value = (sbyte)stream.ReadByte(); break;
                case Types.TYPE_UINT_8: value = (byte)stream.ReadByte(); break;
                case Types.TYPE_INT_16: value = ReadNumber<short>(stream); break;
                case Types.TYPE_UINT_16: value = ReadNumber<ushort>(stream); break;
                case Types.TYPE_INT_32: value = ReadNumber<int>(stream); break;
                case Types.TYPE_UINT_32: value = ReadNumber<uint>(stream); break;
                case Types.TYPE_INT_64: value = ReadNumber<long>(stream); break;
                case Types.TYPE_UINT_64: value = ReadNumber<ulong>(stream); break;
                case Types.TYPE_FLOAT: value = ReadNumber<float>(stream); break;
                case Types.TYPE_DOUBLE: value = ReadNumber<double>(stream); break;
                case Types.TYPE_STRING_8: value = ReadString8(stream); break;
                case Types.TYPE_STRING_16: value = ReadString16(stream); break;
                case Types.TYPE_STRING_32: value = ReadString32(stream); break;
                case Types.TYPE_BINARY_8: value = ReadBinary8(stream); break;
                case Types.TYPE_BINARY_16: value = ReadBinary16(stream); break;
                case Types.TYPE_BINARY_32: value = ReadBinary32(stream); break;
                case Types.TYPE_STREAM_8: value = ReadStream8(stream); break;
                case Types.TYPE_STREAM_16: value = ReadStream16(stream); break;
                case Types.TYPE_STREAM_32: value = ReadStream32(stream); break;
                case Types.TYPE_DATETIME: value = ReadDateTime(stream); break;
                case Types.TYPE_GUID: value = ReadGuid(stream); break;
                case Types.TYPE_ARRAY_8: value = ReadArray8(stream, type);break;
                case Types.TYPE_ARRAY_16:value = ReadArray16(stream, type);break;
                case Types.TYPE_ARRAY_32:value = ReadArray32(stream, type);break;
                case Types.TYPE_LIST_8:value = ReadList8(stream, type);break;
                case Types.TYPE_LIST_16:value = ReadList16(stream, type);break;
                case Types.TYPE_LIST_32:value = ReadList32(stream, type);break;
                case Types.TYPE_MAP_8:value = ReadMap8(stream, type);break;
                case Types.TYPE_MAP_16:value = ReadMap16(stream, type);break;
                case Types.TYPE_MAP_32:value = ReadMap32(stream, type);break;                
                case Types.TYPE_CODED_MAP_8:
                case Types.TYPE_CODED_MAP_16:
                case Types.TYPE_CODED_MAP_32:
                    value = ReadCodedMap(stream, typeCode, type);
                    break;
                case Types.TYPE_DECIMAL:
                    value = ReadNumber<decimal>(stream);
                    break;
                default:
                    throw new NotSupportedException($"TYPE CODE {typeByte} not supported");
            }
         
            return BinaryConvert.ConvertTo(type, value);
        }

19 View Source File : Stream.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public virtual int ReadByte()
        {
            return M_Stream.ReadByte();
        }

19 View Source File : StreamUtils.cs
License : MIT License
Project Creator : ansel86castro

public static byte ReadByte(Stream stream)
        {
            return (byte)stream.ReadByte();
        }

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

public override int ReadByte() {
            int read = Inner.ReadByte();
            if (read >= 0)
                _Position++;
            return read;
        }

19 View Source File : Hash.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static ushort ReadUShort(Stream stream)
            {
                return (ushort)(stream.ReadByte() + (stream.ReadByte() << 8));
            }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void circularShift(int bits, bool leftShift)
        {
            if (!ValidPositionWhen(8))
            {
                throw new IOException("Cannot read in an offset bigger than the length of the stream");
            }
            Seek(offset, 0);
            if (bits != 0 && bits <= 7)
            {
                byte value = (byte)stream.ReadByte();
                if (leftShift)
                {
                    value = (byte)(value << bits | value >> (8 - bits));
                }
                else
                {
                    value = (byte)(value >> bits | value << (8 - bits));
                }
                Seek(offset, 0);
                stream.WriteByte(value);
            }
            bit = 0;
            offset++;
        }

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

public void Normalize2()
		{
			if (Range < kTopValue)
			{
				Code = (Code << 8) | (byte)Stream.ReadByte();
				Range <<= 8;
			}
		}

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

public override int ReadByte() => Inner.ReadByte();

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

private static Endianess? TryDetectTiffByteOrder(Stream stream)
        {
            int byte1 = stream.ReadByte();
            if (byte1 == -1)
            {
                return null;
            }

            int byte2 = stream.ReadByte();
            if (byte2 == -1)
            {
                return null;
            }

            ushort byteOrderMarker = (ushort)(byte1 | (byte2 << 8));

            if (byteOrderMarker == TiffConstants.BigEndianByteOrderMarker)
            {
                return Endianess.Big;
            }
            else if (byteOrderMarker == TiffConstants.LittleEndianByteOrderMarker)
            {
                return Endianess.Little;
            }
            else
            {
                return null;
            }
        }

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

private static IObservable<byte[]> CreateByteStreamObservable2(Stream stream, TcpClient tcpClient, CancellationToken ct)
        {
            var observableBytes = Observable.Create<byte[]>(obs =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (ct.IsCancellationRequested || !tcpClient.Connected)
                    {
                        obs.OnNext(Enumerable.Empty<byte>().ToArray());
                    }

                    var oneByteArray = new byte[1];

                    try
                    {
                        if (stream == null)
                        {
                            throw new Exception("Read stream cannot be null.");
                        }

                        if (!stream.CanRead)
                        {
                            throw new Exception("Stream connection have been closed.");
                        }

                        var bytesRead = stream.ReadByte();

;                        //var bytesRead = await stream.ReadAsync(oneByteArray, 0, 1, ct).ConfigureAwait(false);

                        if (bytesRead < oneByteArray.Length)
                        {
                            throw new Exception("Stream connection aborted unexpectedly. Check connection and socket security version/TLS version).");
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception.");
                        obs.OnNext(Enumerable.Empty<byte>().ToArray());
                    }
                    catch (IOException)
                    {
                        obs.OnNext(Enumerable.Empty<byte>().ToArray());
                    }

                    obs.OnNext(oneByteArray);
                }

                obs.OnCompleted();

                return Disposable.Empty;
            });

            return observableBytes.SubscribeOn(Scheduler.Default);
        }

19 View Source File : FileReader.cs
License : MIT License
Project Creator : Abdesol

static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding)
		{
			int max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB
			const int ASCII = 0;
			const int Error = 1;
			const int UTF8 = 2;
			const int UTF8Sequence = 3;
			int state = ASCII;
			int sequenceLength = 0;
			byte b;
			for (int i = 0; i < max; i++) {
				if (i == 0) {
					b = firstByte;
				} else if (i == 1) {
					b = secondByte;
				} else {
					b = (byte)fs.ReadByte();
				}
				if (b < 0x80) {
					// normal ASCII character
					if (state == UTF8Sequence) {
						state = Error;
						break;
					}
				} else if (b < 0xc0) {
					// 10xxxxxx : continues UTF8 byte sequence
					if (state == UTF8Sequence) {
						--sequenceLength;
						if (sequenceLength < 0) {
							state = Error;
							break;
						} else if (sequenceLength == 0) {
							state = UTF8;
						}
					} else {
						state = Error;
						break;
					}
				} else if (b >= 0xc2 && b < 0xf5) {
					// beginning of byte sequence
					if (state == UTF8 || state == ASCII) {
						state = UTF8Sequence;
						if (b < 0xe0) {
							sequenceLength = 1; // one more byte following
						} else if (b < 0xf0) {
							sequenceLength = 2; // two more bytes following
						} else {
							sequenceLength = 3; // three more bytes following
						}
					} else {
						state = Error;
						break;
					}
				} else {
					// 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629)
					state = Error;
					break;
				}
			}
			fs.Position = 0;
			switch (state) {
				case ASCII:
					return new StreamReader(fs, IsASCIICompatible(defaultEncoding) ? RemoveBOM(defaultEncoding) : Encoding.ASCII);
				case Error:
					// When the file seems to be non-UTF8,
					// we read it using the user-specified encoding so it is saved again
					// using that encoding.
					if (IsUnicode(defaultEncoding)) {
						// the file is not Unicode, so don't read it using Unicode even if the
						// user has choosen Unicode as the default encoding.

						defaultEncoding = Encoding.Default; // use system encoding instead
					}
					return new StreamReader(fs, RemoveBOM(defaultEncoding));
				default:
					return new StreamReader(fs, UTF8NoBOM);
			}
		}

19 View Source File : RawReader.cs
License : MIT License
Project Creator : aljazsim

public override int ReadByte()
        {
            if (this.hasPeek)
            {
                this.hasPeek = false;

                return this.peeked[0];
            }
            else
            {
                return base.ReadByte();
            }
        }

See More Examples