ReadByte() public method

public ReadByte ( ) : int
return int
Esempio n. 1
0
        public override void ReadContents(byte[] bytes)
        {
            using (var ms = new MemoryStream(bytes))
            {
                if (ms.Length == 0)
                {
                    _emptyPayload = true;
                    Payload = new byte[] {};
                }
                else
                {
                    _emptyPayload = false;

                    var audioByte = (byte) ms.ReadByte();

                    _audioFormat = (AudioFormat) (audioByte >> 4 & 0x0f);
                    _audioRate = (AudioRate) (audioByte >> 2 & 0x03);
                    _audioSize = (AudioSize) (audioByte >> 1 & 0x01);
                    _audioType = (AudioType) (audioByte & 0x01);

                    if (_audioFormat == AudioFormat.AAC)
                    {
                        if (_audioRate == AudioRate._44kH || _audioType == AudioType.Stereo)
                        {
                            _aacPacketType = (AACPacketType) ms.ReadByte();
                        }
                    }

                    Payload = new byte[ms.Length - ms.Position];
                    ms.Read(Payload, 0, Payload.Length);
                }
            }
        }
Esempio n. 2
0
 static void DecodeAppleBitmaps(string[] paths)
 {
     foreach (string path in paths)
         if (File.Exists(path))
         {
             byte[] allbytes = File.ReadAllBytes(path);
             MemoryStream ms = new MemoryStream(allbytes);
             ms.Position = 0;
             int HeaderLength = ReadInt(ref ms);
             int ImageWidth = ReadInt(ref ms);
             int ImageHeight = ReadInt(ref ms);
             while (ms.Position < HeaderLength)
                 ms.ReadByte();
             Bitmap bmp = new Bitmap(ImageWidth, ImageHeight);
             for (int i = 0; i < ImageWidth * ImageHeight; i++)
             {
                 byte B = (byte)(ms.ReadByte() & 0xFF);
                 byte G = (byte)(ms.ReadByte() & 0xFF);
                 byte R = (byte)(ms.ReadByte() & 0xFF);
                 byte A = (byte)(ms.ReadByte() & 0xFF);
                 bmp.SetPixel(i % ImageWidth, i / ImageWidth, Color.FromArgb(A, R, G, B));
             }
             bmp.Save(path + ".png");
         }
 }
Esempio n. 3
0
 internal static byte[] Cipher(byte[] buffer, ref byte[] key, bool decrypt)
 {
     var cipher = new Blowfish(key);
     var b = new byte[8];
     using (var m = new MemoryStream(buffer, true))
     {
         while (m.Position < m.Length)
         {
             //Endian swap 2 sets of 4 bytes
             for (int i = 3; i >= 0; i--)
             {
                 b[i] = (byte)m.ReadByte();
             }
             for (int i = 7; i >= 4; i--)
             {
                 b[i] = (byte)m.ReadByte();
             }
             //cipher the 8 bytes
             if (decrypt) cipher.Decipher(b, 8);
             else cipher.Encipher(b, 8);
             //Reset stream position to prepare for writing.
             m.Position -= 8;
             //Endian swap 4 bytes twice
             for (int i = 3; i >= 0; i--)
             {
                 m.WriteByte(b[i]);
             }
             for (int i = 7; i >= 4; i--)
             {
                 m.WriteByte(b[i]);
             }
         }
     }
     return buffer;
 }
Esempio n. 4
0
        /// <summary>
        /// Parses the given packet contained in the byte buffer array and returns
        /// a list of packets
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static LinkedList<AMFDataType> getPacketVars(byte[] buffer, int length, int offset)
        {
            //the linked list of packet vars
            LinkedList<AMFDataType> packetVars = new LinkedList<AMFDataType>();

            //read the header byte to determine size
            MemoryStream packetStream = new MemoryStream(buffer, offset, length);

            byte header = (byte)packetStream.ReadByte();
            header &= 0xC0; // isolate the size information

            //seek into the packet
            packetStream.Seek(AMFHeader.getHeaderSize(header) - 1, SeekOrigin.Current);

            while (packetStream.Position < length)
            {
                byte type = (byte)packetStream.ReadByte();
                Console.WriteLine("Looking at type: " + type);
                AMFDataType var = findAppropriateReader(type);
                var.read(packetStream);
                packetVars.AddLast(var);

            }
            

            return packetVars;

        }
        public Unsubscribe(List<byte> packetList)
        {
            TopicNames = new List<string>();
            packetList.RemoveAt(0);
            MemoryStream stream = new MemoryStream(packetList.ToArray());
            int remainingPacketLength = decodeRemainingLength(ref stream);
            PacketId = fromMsbLsb((byte)stream.ReadByte(), (byte)stream.ReadByte());

            while (remainingPacketLength > 0)
            {
                int thisTopicNameLength = fromMsbLsb((byte)stream.ReadByte(), (byte)stream.ReadByte());
                remainingPacketLength -= 2;
                string thisTopicName = string.Empty;
                for (var i = 0; i < thisTopicNameLength; i++)
                {
                    char c = (char)stream.ReadByte();
                    if(_validChars.Contains(c))
                        thisTopicName += c;
                    else
                        return;

                    remainingPacketLength--;
                }
                TopicNames.Add(thisTopicName);
            }
        }
        public override void Parse(MemoryStream ms, ParseState state)
        {
            /* eat the try byte */
            ms.ReadByte();
            state.AlternateBreak = 102;
            while (Peek(ms) != 102)
            {
                Element nextElement = Element.GetNextElement(ms, state, IndentLevel, true);
                Body.Add(nextElement);
            }

            while (Peek(ms) != 103)
            {
                CatchElement catchElem = new CatchElement();
                catchElem.IndentLevel = IndentLevel;
                catchElem.Parse(ms, state);
                Catches.Add(catchElem);
            }

            /* eat the end try */
            ms.ReadByte();

            /* eat the semicolon */
            ms.ReadByte();
        }
Esempio n. 7
0
        private void doPsByte(byte[] psDate)
        {
            if (!(psDate[0] == 0 && psDate[1] == 0 && psDate[2] == 1 && psDate[3] == 0xBA))
            {
                Console.WriteLine("出错了!!!!!!!!");
            }
            long   scr      = 0;
            Stream msStream = new System.IO.MemoryStream(psDate);

            var ph = new PSPacketHeader(msStream);

            scr = ph.GetSCR();
            List <PESPacket> videoPESList = new List <PESPacket>();

            while (msStream.Length - msStream.Position > 4)
            {
                bool findStartCode = msStream.ReadByte() == 0x00 && msStream.ReadByte() == 0x00 && msStream.ReadByte() == 0x01 && msStream.ReadByte() == 0xE0;
                if (findStartCode)
                {
                    msStream.Seek(-4, SeekOrigin.Current);
                    var pesVideo = new PESPacket();
                    pesVideo.SetBytes(msStream);
                    var esdata = pesVideo.PES_Packet_Data;
                    videoPESList.Add(pesVideo);
                }
            }
            msStream.Close();
            HandlES(videoPESList);
        }
        public override void Parse(MemoryStream ms, ParseState state)
        {
            /* eat the declare byte */
            ms.ReadByte();

            StringBuilder sb = new StringBuilder();
            sb.Append("Declare Function ");
            ms.Position += 1;

            Element.GetNextElement(ms, state, -1).Write(sb);

            sb.Append(" ");

            /* eat the "peoplecode" byte */
            ms.ReadByte();

            sb.Append("PeopleCode ");

            Element.GetNextElement(ms, state, -1).Write(sb);

            sb.Append(" ");

            Element.GetNextElement(ms, state, -1).Write(sb);

            sb.Append(";\r\n");

            Value = sb.ToString();

            /* eat 2 bytes */
            ms.Position += 2;
        }
        public void ShouldDownloadFile()
        {
            var f = Encoding.ASCII.GetBytes(new string('x', 1048576));

            using (var fileContents = new MemoryStream(f))
            {
                var parent = Client.CreateFolder(FolderID.Root, "ParentFolder").ID;
                var file = Client.CreateFile(parent, "DownloadFileTest").ID;

                var progress = Client.StartUpload(file, fileContents);

                while (!progress.EOFReached)
                {
                    progress = Client.UploadContent(file, progress, fileContents);
                }
                Client.FinishUpload(file, progress);

                using (var downloadContents = Client.DownloadFileContent(file))
                {
                    fileContents.Seek(0, SeekOrigin.Begin);

                    int b1 = downloadContents.ReadByte(), b2 = fileContents.ReadByte();
                    do
                    {
                        Assert.AreEqual(b1, b2);
                        b1 = downloadContents.ReadByte();
                        b2 = fileContents.ReadByte();
                    } while (b1 != -1 && b2 != -1);
                }
            }
        }
        public Publish(List<byte> packetList)
        {
            packetList.RemoveAt(0); // remove the type which we know already
            MemoryStream stream = new MemoryStream(packetList.ToArray());
            int numberOfChars = decodeRemainingLength(ref stream);

            int topicNameLength = fromMsbLsb((byte)stream.ReadByte(), (byte)stream.ReadByte());

            TopicName = string.Empty;
            for(int i = 0; i < topicNameLength; i++)
            {
                char c = (char) stream.ReadByte();

                if(c != '\0')
                    TopicName += c;
            }

            int remainingLength = numberOfChars - 2 - topicNameLength; // -2 for topic name length MSB+LSB
            Payload = string.Empty;
            for (int i = 0; i < remainingLength; i++)
            {
                char c = (char) stream.ReadByte();
                if(c != '\0')
                    Payload += c;
            }
            stream.Close();
        }
        public override void Parse(MemoryStream ms, ParseState state)
        {
            /* eat the While byte */
            ms.ReadByte();

            byte nextByte = Peek(ms);
            while (nextByte != 45) /* new line */
            {
                Condition.Add(Element.GetNextElement(ms, state, IndentLevel));
                nextByte = Peek(ms);
            }

            /* eat the new line */
            ms.ReadByte();

            nextByte = Peek(ms);
            state.AlternateBreak = 38;
            while (nextByte != 38) /* end-while */
            {
                Body.Add(Element.GetNextElement(ms, state, IndentLevel,true));
                nextByte = Peek(ms);
            }

            /* eat the end while */
            ms.ReadByte();

            /* eat the semicolon */
            ms.ReadByte();
        }
Esempio n. 12
0
        public static string ConvertFromPHP(string sPHP)
        {
            XmlDocument xml = new XmlDocument();
            xml.AppendChild(xml.CreateProcessingInstruction("xml" , "version=\"1.0\" encoding=\"UTF-8\""));
            xml.AppendChild(xml.CreateElement("USER_PREFERENCE"));
            try
            {
                byte[] abyPHP = Convert.FromBase64String(sPHP);
                StringBuilder sb = new StringBuilder();
                foreach(char by in abyPHP)
                    sb.Append(by);
                MemoryStream mem = new MemoryStream(abyPHP);

                string sSize = String.Empty;
                int nChar = mem.ReadByte();
                while ( nChar != -1 )
                {
                    char ch = Convert.ToChar(nChar);
                    if ( ch == 'a' )
                        PHPArray(xml, xml.DocumentElement, mem);
                    else if ( ch == 's' )
                        PHPString(mem);
                    else if ( ch == 'i' )
                        PHPInteger(mem);
                    nChar = mem.ReadByte();
                }
            }
            catch(Exception ex)
            {
                SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message);
            }
            return xml.OuterXml;
        }
Esempio n. 13
0
        /// <summary>
        /// Creates a new NBT reader with a specified memory stream.
        /// </summary>
        /// <param name="memIn">The memory stream in which the NBT is located.</param>
        /// <param name="version">The compression version of the NBT, choose 1 for GZip and 2 for ZLib.</param>
        public NBTReader(MemoryStream memIn, int version)
        {
            /*  Due to a file specification change on how an application reads a NBT file
             *  (Minecraft maps are now compressed via a z-lib deflate stream), this method
             *  provides backwards support for the old GZip decompression stream (in case for raw NBT files
             *  and old Minecraft chunk files).
             */

            // meaning the NBT is compressed via a GZip stream
            if (version == 1)
            {
                // decompress the stream
                GZipStream gStream = new GZipStream(memIn, CompressionMode.Decompress);

                // route the stream to a binary reader
                _bRead = new BinaryReader(memIn);
            }
            // meaning the NBT is compressed via a z-lib stream
            else if (version == 2)
            {
                // a known bug when deflating a zlib stream...
                // for more info, go here: http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html
                memIn.ReadByte();
                memIn.ReadByte();

                // deflate the stream
                DeflateStream dStream = new DeflateStream(memIn, CompressionMode.Decompress);

                // route the stream to a binary reader
                _bRead = new BinaryReader(dStream);
            }
        }
        public Connect(List<byte> packetList)
        {
            packetList.RemoveAt(0); // remove packet type
            MemoryStream stream = new MemoryStream(packetList.ToArray());
            int numberOfChars = decodeRemainingLength(ref stream);

            int protocolNameLength = fromMsbLsb((byte) stream.ReadByte(), (byte) stream.ReadByte());

            ProtocolName = string.Empty;
            for (int i = 0; i < protocolNameLength; i++)
            {
                char c = (char)stream.ReadByte();

                if (c != '\0')
                    ProtocolName += c;
            }

            ProtocolVersion = (byte) stream.ReadByte();
            // possibly check for the protocol level

            ConnectFlags = (byte) stream.ReadByte();

            KeepAliveTime = fromMsbLsb((byte) stream.ReadByte(), (byte) stream.ReadByte());

            int clientIdLength = fromMsbLsb((byte)stream.ReadByte(), (byte)stream.ReadByte());

            ClientId = string.Empty;
            for (int i = 0; i < clientIdLength; i++)
            {
                char c = (char)stream.ReadByte();
                if (c != '\0')
                    ClientId += c;
            }
        }
Esempio n. 15
0
        public static void unescapeNAL(System.IO.MemoryStream _buf)
        {
            if (_buf.Position - _buf.Length < 2)
            {
                return;
            }
            System.IO.MemoryStream inb  = new System.IO.MemoryStream(_buf.ToArray());
            System.IO.MemoryStream outb = new System.IO.MemoryStream(_buf.ToArray());
            byte p1 = (byte)inb.ReadByte();

            outb.WriteByte(p1);
            byte p2 = (byte)inb.ReadByte();

            outb.WriteByte(p2);
            while (inb.Position < inb.Length)
            {
                byte b = (byte)inb.ReadByte();
                if (p1 != 0 || p2 != 0 || b != 3)
                {
                    outb.WriteByte(b);
                }
                p1 = p2;
                p2 = b;
            }
            _buf.SetLength(outb.Position);
        }
Esempio n. 16
0
        public void FlushBitsTest()
        {
            var mem = new MemoryStream();
            var writer = new SwfStreamWriter(mem);

            writer.WriteBit(true);
            writer.WriteBit(false);
            writer.WriteBit(true);
            writer.WriteBit(false);
            writer.WriteBit(true);
            writer.WriteBit(false);
            writer.WriteBit(true);
            writer.WriteBit(false);

            writer.WriteBit(true);
            writer.WriteBit(true);
            writer.WriteBit(false);
            writer.WriteBit(false);
            writer.WriteBit(false);
            writer.WriteBit(false);

            writer.FlushBits();

            mem.Seek(0, SeekOrigin.Begin);

            Assert.AreEqual(0xaa, mem.ReadByte(), "Byte 0");
            Assert.AreEqual(0xc0, mem.ReadByte(), "Byte 1");

            Assert.AreEqual(mem.Length, mem.Position, "Should reach end of the stream");
        }
Esempio n. 17
0
 public override void ReadContents(byte[] bytes)
 {
     using (var ms = new MemoryStream(bytes))
     {
         var typeByte = (byte) ms.ReadByte();
         FrameType = (FrameType) (typeByte >> 4);
         Codec = (Codec) (typeByte & 0x0f);
         AVCType = AvcType.NotSet;
         if (Codec == Codec.AVC)
         {
             AVCType = (AvcType) ms.ReadByte();
             if (bytes.Length >= 5)
             {
                 switch (AVCType)
                 {
                     case AvcType.Nalu:
                         CompositionTime = Utils.GetUInt24(ms.ReadBytes(3), 0);
                         break;
                     default:
                         CompositionTime = Utils.GetUInt24(ms.ReadBytes(3), 0);
                         break;
                 }
             }
         }
         Payload = new byte[ms.Length - ms.Position];
         ms.Read(Payload, 0, Payload.Length);
     }
 }
        /// <summary>
        /// Convert a byte array to a DotSpatial.Topology geometry object
        /// </summary>
        /// <param name="data">the data from the BLOB column</param>
        /// <returns>the geometry object</returns>
        public override IGeometry Read(byte[] data)
        {
            //specialized Read() method for SpatiaLite
            using (Stream stream = new MemoryStream(data))
            {
                //read first byte
                BinaryReader reader = null;
                var startByte = stream.ReadByte(); //must be "0"
                var byteOrder = (ByteOrder)stream.ReadByte();

                try
                {
                    reader = (byteOrder == ByteOrder.BigEndian) ? new BeBinaryReader(stream) : new BinaryReader(stream);

                    int srid = reader.ReadInt32();
                    double mbrMinX = reader.ReadDouble();
                    double mbrMinY = reader.ReadDouble();
                    double mbrMaxX = reader.ReadDouble();
                    double mbrMaxY = reader.ReadDouble();
                    byte mbrEnd = reader.ReadByte();

                    return Read(reader);
                }
                finally
                {
                    if (reader != null)
                        reader.Close();
                }
            }
        }
Esempio n. 19
0
        private void Init(byte[] buffer)
        {
            var stream = new MemoryStream(buffer);
            stream.Seek(0, SeekOrigin.Begin);
            if (stream.ReadByte() != 2 && stream.ReadByte() != 0)
            {
                throw new InvalidDataException("Error Table Index");
            }
            else
            {
                while(ReadOne(stream))
                {
                    continue;
                }
                stream.Seek(195, SeekOrigin.Begin);
                if (stream.ReadByte() != 3)
                {
                    throw new InvalidDataException("Error Table Index");
                }
                else
                {

                }
            }
        }
        public Unsuback(List<byte> packetList)
        {
            packetList.RemoveAt(0);
            MemoryStream stream = new MemoryStream(packetList.ToArray());
            int remainingLengthOfPacket = decodeRemainingLength(ref stream);

            PacketId = fromMsbLsb((byte) stream.ReadByte(), (byte) stream.ReadByte());
        }
        public override void Parse(MemoryStream ms, ParseState state)
        {
            /* eat the Local byte */
            byte variableType = (byte)ms.ReadByte();

            switch(variableType)
            {
                case 68:
                    declareType = DeclareType.LOCAL;
                    break;
                case 69:
                    declareType = DeclareType.GLOBAL;
                    break;
                case 84:
                    declareType = DeclareType.COMPONENT;
                    break;
                case 86:
                    declareType = DeclareType.CONSTANT;
                    break;
                case 98:
                    declareType = DeclareType.INSTANCE;
                    break;
            }

            byte nextByte = Peek(ms);
            Element stringElement = new PureStringElement();
            StringBuilder sb = new StringBuilder();
            if (declareType != DeclareType.CONSTANT)
            {
                while (nextByte != 1)
                {
                    var e = Element.GetNextElement(ms, state, -1);

                    if (e.Value == ":" && sb[sb.Length - 1] == ' ')
                    {
                        sb.Length--;
                    }

                    e.Write(sb);
                    if (e.Value != ":" && sb[sb.Length-1] != ':')
                    {
                        sb.Append(" ");
                    }

                    nextByte = Peek(ms);
                }

                VariableType = sb.ToString().Trim();
            }
            while (nextByte != 21) /* semicolon */
            {
                Declaration.Add(GetNextElement(ms, state, 0));
                nextByte = Peek(ms);
            }
            /* eat the semicolon */
            ms.ReadByte();
        }
Esempio n. 22
0
        protected internal virtual void assertEquals(MemoryStream expected, MemoryStream actual)
        {
            int fromActual;
            while ((fromActual = actual.ReadByte()) != - 1)
            {
                Assert.AreEqual(expected.ReadByte(), fromActual);
            }

            Assert.AreEqual(expected.ReadByte(), -1);
        }
Esempio n. 23
0
        public DeviceInformation(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);

            this.contactDescriptorByteValue =(byte) ms.ReadByte();
            this.ipStrLength = (byte)ms.ReadByte();
            byte[] buff = new byte[this.ipStrLength];
            ms.Read(buff, 0, this.ipStrLength);
            this.ipAddr = Encoding.ASCII.GetString(buff);
        }
Esempio n. 24
0
 protected override void ParseData(MemoryStream ms)
 {
     Width = Helper.ConvertEndian(ms.ReadInt32());
     Height = Helper.ConvertEndian(ms.ReadInt32());
     BitDepth = Convert.ToByte(ms.ReadByte());
     ColorType = Convert.ToByte(ms.ReadByte());
     CompressionMethod = Convert.ToByte(ms.ReadByte());
     FilterMethod = Convert.ToByte(ms.ReadByte());
     InterlaceMethod = Convert.ToByte(ms.ReadByte());
 }
 public GetWalletPubKeyResponse(byte[] bytes)
 {
     MemoryStream ms = new MemoryStream(bytes);
     var len = ms.ReadByte();
     UncompressedPublicKey = new PubKey(ms.ReadBytes(len));
     len = ms.ReadByte();
     var addr = Encoding.ASCII.GetString(ms.ReadBytes(len));
     Address = BitcoinAddress.GetFromBase58Data(addr);
     ChainCode = ms.ReadBytes(32);
 }
Esempio n. 26
0
        public static int Write(Level level, Stream file, string fileName, string guid)
        {
            string result;
            fileName += "_data_";
            guid = "data_" + guid;
            int length = 0;
            using (MemoryStream memStream = new MemoryStream())
            {
                StringBuilder builder = new StringBuilder();

                using (BinaryWriter writer = new BinaryWriter(memStream))
                {
                    level.Write(writer);
                    length = (int)memStream.Length;
                    memStream.Seek(0, SeekOrigin.Begin);

                    builder.Append("\n@{{BLOCK(" + guid + ")\n\n");
                    builder.Append("\t.section .rodata\n");
                    builder.Append("\t.align 2\n");
                    builder.Append("\t.global " + guid + " @ " + memStream.Length + " bytes\n");
                    builder.Append(guid + ":\n");

                    long dqwords = memStream.Length / 16;
                    long mod = memStream.Length % 16;

                    for (long i = 0; i < dqwords; ++i)
                    {
                        builder.Append("\t.byte ");
                        int read = memStream.ReadByte();
                        byte tempByte = (byte)(read & 0xFF);
                        builder.Append("0x" + tempByte.ToString("X02"));

                        for (int j = 1; j < 16; ++j)
                        {
                            builder.Append(",0x" + ((byte)memStream.ReadByte()).ToString("X02"));
                        }
                        builder.Append('\n');
                    }

                    if (mod > 0)
                    {
                        builder.Append("\t.byte 0x" + ((byte)memStream.ReadByte()).ToString("X02"));
                        for (int i = 1; i < mod; ++i)
                            builder.Append(",0x" + ((byte)memStream.ReadByte()).ToString("X02"));
                    }
                    builder.Append("\n\n@}}BLOCK(" + guid + ")\n");
                }
                result = builder.ToString();
            }

            byte[] arr = Encoding.ASCII.GetBytes(result);
            file.Write(arr, 0, arr.Length);

            return length;
        }
Esempio n. 27
0
        public static byte[] DecodeQuotePrintable(byte[] data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            var msRetVal = new MemoryStream();
            var msSourceStream = new MemoryStream(data);

            int b = msSourceStream.ReadByte();
            while (b > -1)
            {
                // Encoded 8-bit byte(=XX) or soft line break(=CRLF)
                if (b == '=')
                {
                    byte[] buffer = new byte[2];
                    int nCount = msSourceStream.Read(buffer, 0, 2);
                    if (nCount == 2)
                    {
                        // Soft line break, line splitted, just skip CRLF
                        if (buffer[0] == '\r' && buffer[1] == '\n')
                        {
                        }
                        // This must be encoded 8-bit byte
                        else
                        {
                            try
                            {
                                msRetVal.Write(FromHex(buffer), 0, 1);
                            }
                            catch
                            {
                                // Illegal value after =, just leave it as is
                                msRetVal.WriteByte((byte)'=');
                                msRetVal.Write(buffer, 0, 2);
                            }
                        }
                    }
                    // Illegal =, just leave as it is
                    else
                    {
                        msRetVal.Write(buffer, 0, nCount);
                    }
                }
                // Just write back all other bytes
                else
                {
                    msRetVal.WriteByte((byte)b);
                }

                // Read next byte
                b = msSourceStream.ReadByte();
            }

            return msRetVal.ToArray();
        }
Esempio n. 28
0
        public Message(byte[] messageBytes)
        {
            var stream = new MemoryStream(messageBytes, false);

            //Message type x 1
            this.Type = (MessageType)stream.ReadByte();

            //Length of source x 1
            int fromLength = stream.ReadByte();

            //Source x N
            var sourceBytes = new byte[fromLength];
            stream.Read(sourceBytes, 0, sourceBytes.Length);
            this.Source = Encoding.UTF8.GetString(sourceBytes);

            //Length of target x 1
            int toLength = stream.ReadByte();

            //Target x N
            var targetBytes = new byte[toLength];
            stream.Read(targetBytes, 0, targetBytes.Length);
            this.Target = Encoding.UTF8.GetString(targetBytes);

            //Length of path x 2
            var pathLenBytes = new byte[2];
            stream.Read(pathLenBytes, 0, pathLenBytes.Length);
            short pathLen = BitConverter.ToInt16(pathLenBytes, 0);

            //Path x N
            var pathBytes = new byte[pathLen];
            stream.Read(pathBytes, 0, pathBytes.Length);
            this.Path = Encoding.UTF8.GetString(pathBytes);

            //SessionID x 32
            var sessionBytes = new byte[32];
            stream.Read(sessionBytes, 0, sessionBytes.Length);
            this.SessionId = Encoding.UTF8.GetString(sessionBytes);

            //Overtime x 2
            var timeoutBytes = new byte[2];
            stream.Read(timeoutBytes, 0, timeoutBytes.Length);
            this.Timeout = BitConverter.ToInt16(timeoutBytes, 0);

            //Length of Data x 4
            var dataLenBytes = new byte[4];
            stream.Read(dataLenBytes, 0, dataLenBytes.Length);
            int dataLen = BitConverter.ToInt32(dataLenBytes, 0);

            //Data x N
            this.Data = new byte[dataLen];
            stream.Read(this.Data, 0, this.Data.Length);

            stream.Close();
        }
Esempio n. 29
0
 protected static Stream GetDataStream(byte[] rawData, int offset, int length, bool compressed)
 {
     MemoryStream stream = new MemoryStream();
     stream.Write(rawData, offset, length);
     stream.Seek(0, SeekOrigin.Begin);
     if (!compressed)
         return stream;
     stream.ReadByte();
     stream.ReadByte();
     return new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress, false);
 }
        public override void Parse(MemoryStream ms, ParseState state)
        {
            /* eat import byte */
            ms.ReadByte();

            while (Peek(ms) != 21) /* semicolon */
            {
                Import += Element.GetNextElement(ms, state, 0).Value;
            }
            /* eat semicolon */
            ms.ReadByte();
        }
 private void ReadProtocolInformation(MemoryStream mem)
 {
     ProtocolInformationMajorVersion version = (ProtocolInformationMajorVersion) ((byte) mem.ReadByte());
     if (version != ProtocolInformationMajorVersion.v1)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(Microsoft.Transactions.SR.GetString("ProtocolInfoUnsupportedVersion", new object[] { version })));
     }
     ProtocolInformationMinorVersion version2 = (ProtocolInformationMinorVersion) ((byte) mem.ReadByte());
     this.flags = (ProtocolInformationFlags) ((byte) mem.ReadByte());
     this.CheckFlags(this.flags);
     this.httpsPort = SerializationUtils.ReadInt(mem);
     if ((this.httpsPort < 0) || (this.httpsPort > 0xffff))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(Microsoft.Transactions.SR.GetString("ProtocolInfoInvalidHttpsPort", new object[] { this.httpsPort })));
     }
     this.maxTimeout = SerializationUtils.ReadTimeout(mem);
     if (this.maxTimeout < TimeSpan.Zero)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(Microsoft.Transactions.SR.GetString("ProtocolInfoInvalidMaxTimeout", new object[] { this.maxTimeout })));
     }
     this.hostName = SerializationUtils.ReadString(mem);
     if (string.IsNullOrEmpty(this.hostName))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(Microsoft.Transactions.SR.GetString("ProtocolInfoInvalidHostName")));
     }
     this.basePath = SerializationUtils.ReadString(mem);
     if (string.IsNullOrEmpty(this.basePath))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(Microsoft.Transactions.SR.GetString("ProtocolInfoInvalidBasePath")));
     }
     this.nodeName = SerializationUtils.ReadString(mem);
     if (string.IsNullOrEmpty(this.nodeName))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(Microsoft.Transactions.SR.GetString("ProtocolInfoInvalidNodeName")));
     }
     byte num = 2;
     if (version2 >= num)
     {
         ProtocolVersion version3 = (ProtocolVersion) SerializationUtils.ReadUShort(mem);
         if (((ushort) (version3 & ProtocolVersion.Version10)) != 0)
         {
             this.isV10Enabled = true;
         }
         if (((ushort) (version3 & ProtocolVersion.Version11)) != 0)
         {
             this.isV11Enabled = true;
         }
     }
     else
     {
         this.isV10Enabled = true;
     }
 }
Esempio n. 32
0
        private void OnGetData(GetDataEventArgs e)
        {
            if (e.MsgID != PacketTypes.NpcStrike)
            {
                return;
            }

            using (MemoryStream data = new MemoryStream(e.Msg.readBuffer, e.Index, e.Length - 1))
            {
                var id = data.ReadInt16();
                var dmg = data.ReadInt16();
                data.ReadSingle();
                data.ReadByte();
                data.ReadByte();

                if (id < 0 || id > Main.maxNPCs)
                {
                    return;
                }

                NPC npc = Main.npc[id];
                if (npc == null)
                {
                    return;
                }

                if (npc.type != NPCID.KingSlime || !npc.active)
                {
                    return;
                }
                if (dmg <= 0)
                {
                    return;
                }

                if (Main.rand == null)
                {
                    Main.rand = new Random((int)DateTime.Now.Ticks);
                }

                for (int i = 0; i < 20; i++)
                {
                    int amt = 4 + Main.rand.Next(1, 5);

                    for (int j = 0; j < amt; j++)
                    {
                        int x = (int)npc.position.X + Main.rand.Next(-80, 81);
                        int y = (int)npc.position.Y + Main.rand.Next(-80, 81);
                        NPC.NewNPC(x, y, NPCID.BlueSlime, 0);
                    }
                }
            }
        }
Esempio n. 33
0
    public static void Main()
    {
        //chave secreta
        byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
        //vetor de inicialização
        byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

        //Stream de memória
        IO.MemoryStream memstream = new IO.MemoryStream(15);
        //Stream de criptografia
        CP.RC2CryptoServiceProvider provider  = new CP.RC2CryptoServiceProvider();
        CP.ICryptoTransform         transform = provider.CreateEncryptor(Key, IV);
        CP.CryptoStreamMode         mode      = CP.CryptoStreamMode.Write;
        CP.CryptoStream             stream    = new CP.CryptoStream(memstream, transform, mode);

        //Lê cada caracter da string
        foreach (char ch in "Isto é um teste")
        {
            stream.WriteByte((Convert.ToByte(ch)));
        }

        int c;

        //Reposiciona o ponteiro para leitura
        memstream.Position = c = 0; //técnica não trivial, mas válida

        while ((c = memstream.ReadByte()) != -1)
        {
            Console.Write((char)c);
        }

        stream.Close();    //Libera a stream (crypto)
        memstream.Close(); //Libera a stream (mem)
    }
Esempio n. 34
0
        static void MemoryStream()
        {
            MemoryStream memory = new System.IO.MemoryStream();

            //write in the memory
            string content = "Hello, this message is a stream in the memory";

            byte[] bytes = Encoding.UTF8.GetBytes(content);
            memory.Write(bytes, 0, bytes.Length);



            //Set the position to the begninig of stream
            memory.Seek(0, SeekOrigin.Begin);

            //Create an byte array to retrieve the memory bytes
            byte[] bytesToRead = new byte[memory.Length];

            int count = memory.Read(bytesToRead, 0, bytesToRead.Length);

            //bytesToRead. When this method returns, contains the specified byte array with the values between offset and(offset +count - 1) replaced by the characters read from the current stream.
            //count. The total number of bytes written into the buffer.This can be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached before any bytes are read.

            for (int i = count; i < memory.Length; i++)
            {
                bytesToRead[i] = Convert.ToByte(memory.ReadByte());
            }


            string message = Encoding.UTF8.GetString(bytesToRead);

            Console.WriteLine(message);
        }
Esempio n. 35
0
        /**
         * Finds next Nth H.264 bitstream NAL unit (0x00000001) and returns the data
         * that preceeds it as a System.IO.MemoryStream slice
         *
         * Segment byte order is always little endian
         *
         * TODO: emulation prevention
         *
         * @param buf
         * @return
         */
        public static System.IO.MemoryStream gotoNALUnit(System.IO.MemoryStream buf)
        {
            if (buf.Position >= buf.Length)
            {
                return(null);
            }

            long from = buf.Position;

            byte[] temp = new byte[buf.Length - buf.Position];

            buf.Read(temp, 0, (int)(buf.Length - buf.Position));

            System.IO.MemoryStream result = new System.IO.MemoryStream(temp);
            //result.order(ByteOrder.BIG_ENDIAN);

            long val = 0xffffffff;

            while (buf.Position < buf.Length)
            {
                val <<= 8;
                val  |= (buf.ReadByte() & 0xff);
                if ((val & 0xffffff) == 1)
                {
                    buf.Position = buf.Position - (val == 1 ? 4 : 3);
                    result.SetLength(buf.Position - from);
                    break;
                }
            }
            return(result);
        }
Esempio n. 36
0
            private void copyDataCAVLC(System.IO.MemoryStream iss, System.IO.MemoryStream os, BitReader reader, BitWriter writer)
            {
                int wLeft = 8 - writer.curBit();

                if (wLeft != 0)
                {
                    writer.writeNBit(reader.readNBit(wLeft), wLeft);
                }
                writer.flush();

                // Copy with shift
                int shift = reader.curBit();

                if (shift != 0)
                {
                    int mShift = 8 - shift;
                    int inp    = reader.readNBit(mShift);
                    reader.stop();

                    while (iss.hasRemaining())
                    {
                        int outb = inp << shift;
                        inp   = iss.ReadByte() & 0xff;
                        outb |= inp >> mShift;

                        os.put((byte)outb);
                    }
                    os.put((byte)(inp << shift));
                }
                else
                {
                    reader.stop();
                    os.put(iss);
                }
            }
Esempio n. 37
0
        /// <summary>
        /// Compacts 3 bytes into 2.
        /// </summary>
        /// <param name="stream">stream to compact from</param>
        private void Compact(System.IO.MemoryStream stream)
        {
            stream.Seek(0, System.IO.SeekOrigin.Begin);

            int tmp = 0;

            while (stream.Position + 3 < stream.Length)
            {
                tmp = (tmp * 40) + stream.ReadByte();

                if (stream.Position > 1 && stream.Position % 3 == 1)
                {
                    tmp++;
                    _Stream.WriteByte((byte)(tmp / 256));
                    _Stream.WriteByte((byte)(tmp % 256));
                    tmp = 0;
                }
            }

            if (stream.Position != stream.Length)
            {
                _Format = EncoderFormat.AsciiLower;
                _Stream.WriteByte((byte)SWITCHASCII);
                _Index -= (int)(stream.Length - stream.Position - 1);
            }
            else if (CanRead())
            {
                _Stream.WriteByte((byte)SWITCHASCII);
            }
        }
Esempio n. 38
0
        private static int readLen(System.IO.MemoryStream dup, int nls)
        {
            switch (nls)
            {
            case 1:
                return(dup.ReadByte() & 0xff);

            case 2:
                return(dup.getShort() & 0xffff);

            case 3:
                return(((dup.getShort() & 0xffff) << 8) | (dup.ReadByte() & 0xff));

            case 4:
                return(dup.getInt());

            default:
                throw new ArgumentException("NAL Unit length size can not be " + nls);
            }
        }
Esempio n. 39
0
        public static void escapeNAL(System.IO.MemoryStream src, System.IO.MemoryStream dst)
        {
            byte p1 = (byte)src.ReadByte(), p2 = (byte)src.ReadByte();

            dst.put(p1);
            dst.put(p2);
            while (src.hasRemaining())
            {
                byte b = (byte)src.ReadByte();
                if (p1 == 0 && p2 == 0 && (b & 0xff) <= 3)
                {
                    dst.put((byte)3);
                    p1 = p2;
                    p2 = 3;
                }
                dst.put(b);
                p1 = p2;
                p2 = b;
            }
        }
Esempio n. 40
0
        private void doPsByte(byte[] psDate)
        {
            Stream           msStream     = new System.IO.MemoryStream(psDate);
            List <PESPacket> videoPESList = new List <PESPacket>();

            while (msStream.Length - msStream.Position > 4)
            {
                bool findStartCode = msStream.ReadByte() == 0x00 && msStream.ReadByte() == 0x00 && msStream.ReadByte() == 0x01 && msStream.ReadByte() == 0xE0;
                if (findStartCode)
                {
                    msStream.Seek(-4, SeekOrigin.Current);
                    var pesVideo = new PESPacket();
                    pesVideo.SetBytes(msStream);
                    var esdata = pesVideo.PES_Packet_Data;
                    videoPESList.Add(pesVideo);
                }
            }
            msStream.Close();
            HandlES(videoPESList);
        }
    static void Main(string[] args)
    {
        var s   = new System.IO.MemoryStream();
        int ret = s.Read(null, 0, 0);

        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        ret = s.Read(null, 0, 0);
        s.Read(null, 0, 0); // always check
        s.ReadByte();       // always check
    }
Esempio n. 42
0
 /*
  * This routine reads bits in from a stream.  The bits are all sitting
  * in a buffer, and this code pulls them out, one at a time.  When the
  * buffer has been emptied, that triggers a new stream read, and the
  * pointers are reset.  This routine is set up to allow for dummy
  * bits/bytes to be read in after the end of of the stream is reached.
  * All be zero(0) valued bits however. This is because we have to keep
  * feeding bits into the pipeline to be decoded so that the old stuff
  * that is 16 bits upstream can be pushed out.
  */
 private ushort input_bit()
 {
     if (input_bits_left == 0)
     {
         if (input_bytes_left > 0)
         {
             current_input_byte = Convert.ToByte(input_buffer.ReadByte());
         }
         else
         {
             return(0);
         }
         input_bytes_left--;
         input_bits_left = 8;
     }
     input_bits_left--;
     return(Convert.ToUInt16((current_input_byte >> input_bits_left) & 1));
 }
Esempio n. 43
0
    static void MemoryStream()
    {
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
        byte[] helloWorldBytes = System.Text.Encoding.Unicode.GetBytes("hello world");
        memoryStream.Write(helloWorldBytes, 0, helloWorldBytes.Length);
        System.Console.WriteLine("Length: " + memoryStream.Length);
        memoryStream.Position = 0;
        int byteReadFromStream;

        System.Collections.Generic.List <byte> list = new System.Collections.Generic.List <byte>();
        while ((byteReadFromStream = memoryStream.ReadByte()) != -1)
        {
            list.Add((byte)byteReadFromStream);
        }
        byte[] bytesFromStream         = list.ToArray();
        string bytesFromStreamAsString = System.Text.Encoding.UTF8.GetString(bytesFromStream);

        System.Console.WriteLine(bytesFromStreamAsString);
    }
Esempio n. 44
0
        private int DisplayMemory(StringBuilder sb, System.IO.MemoryStream ms)
        {
            int  b            = 0;
            long DisplayLimit = ms.Length < 1000L ? ms.Length : 1000;

            for (; ms.Position != DisplayLimit;)
            {
                b = ms.ReadByte();
                if (b == 0)
                {
                    sb.Append("\x1");
                }
                else
                {
                    sb.Append(((char)b).ToString());
                }
            }
            return(b);
        }
Esempio n. 45
0
        public static void skipToNALUnit(System.IO.MemoryStream buf)
        {
            if (!buf.hasRemaining())
            {
                return;
            }

            uint val = 0xffffffff;

            while (buf.Position < buf.Length)
            {
                val <<= 8;
                val  |= (uint)(buf.ReadByte() & 0xff);
                if ((val & 0xffffff) == 1)
                {
                    buf.Position = buf.Position;
                    break;
                }
            }
        }
Esempio n. 46
0
        private static int[] searchEscapeLocations(System.IO.MemoryStream src)
        {
            List <int> points = new List <int>();

            System.IO.MemoryStream search = src.duplicate();
            short p = search.getShort();

            while (search.hasRemaining())
            {
                byte b = (byte)search.ReadByte();
                if (p == 0 && (b & ~3) == 0)
                {
                    points.Add((int)(search.Position - 1));
                    p = 3;
                }
                p <<= 8;
                p  |= (short)(b & 0xff);
            }
            int[] array = points.ToArray();
            return(array);
        }
Esempio n. 47
0
 public override int ReadPayload(System.IO.MemoryStream stream, int length)
 {
     //Debug.Assert(length == 1, "G2PacketHG supposed to read 1 byte but has to read " + length);
     ID = (byte)stream.ReadByte();
     return(1);
 }
Esempio n. 48
0
        private STFSPackage(IFile f)
        {
            Stream input = f.GetStream();

            FileName = f.Name;
            disposed = false;

            stream = input;

            // Set the type of STFS file.
            string magic = stream.ReadASCIINullTerminated(4);

            switch (magic)
            {
            case "CON ":
                Type = STFSType.CON;
                break;

            case "LIVE":
                Type = STFSType.LIVE;
                break;

            case "PIRS":
                Type = STFSType.PIRS;
                break;

            default:
                throw new InvalidDataException("STFS is not CON, LIVE, or PIRS");
            }

            BlockCache = new byte[0x1000];

            // Set up STFS info.
            stream.Position = 0x340;
            headerSize      = stream.ReadInt32BE();

            if ((((headerSize + 0xFFF) & 0xF000) >> 0xC) == 0xB)
            {
                tableSizeShift = 0;
            }
            else
            {
                tableSizeShift = 1;
            }

            // Volume Descriptor begins at 0x379
            stream.Position      = 0x37C;
            fileTableBlockCount  = stream.ReadInt16LE();
            fileTableBlockNumber = stream.ReadInt24LE();

            stream.Position = 0x39D;
            fileCount       = stream.ReadInt32LE();

#if !MINIMAL
            // Read both package thumbnails into Image instances
            stream.Position = 0x1712;
            int thumbnailImgSize      = stream.ReadInt32BE();
            int titleThumbnailImgSize = stream.ReadInt32BE();
            stream.Position = 0x171A;
            if (thumbnailImgSize > 0)
            {
                Thumbnail = System.Drawing.Image.FromStream(new System.IO.MemoryStream(stream.ReadBytes(thumbnailImgSize)));
            }
            stream.Position = 0x571A;
            if (titleThumbnailImgSize > 0)
            {
                TitleThumbnail = System.Drawing.Image.FromStream(new System.IO.MemoryStream(stream.ReadBytes(titleThumbnailImgSize)));
            }
#endif

            root = new STFSDirectory(null, ROOT_DIR);
            var dirsOrdinal = new Dictionary <int, STFSDirectory>();
            dirsOrdinal.Add(-1, root);
            int   items           = 0;
            int[] fileTableBlocks = GetFileBlocks(fileTableBlockNumber, fileTableBlockCount, false);
            for (var x = 0; x < fileTableBlocks.Length; x++)
            {
                var  curBlock = fileTableBlocks[x];
                long basePosition;
                CacheBlockAt(BlockToOffset(curBlock));
                using (var curBlockStream = new System.IO.MemoryStream(BlockCache))
                {
                    for (var i = 0; i < 0x40; i++)
                    {
                        basePosition            = 0x40 * i;
                        curBlockStream.Position = basePosition;
                        if (curBlockStream.ReadByte() == 0)
                        {
                            break;
                        }
                        curBlockStream.Position = basePosition + 0x28;
                        byte flags = (byte)curBlockStream.ReadByte();
                        curBlockStream.Position = basePosition;
                        String name;
                        using (var sr = new System.IO.StreamReader(
                                   new System.IO.MemoryStream(curBlockStream.ReadBytes(flags & 0x3f)), Encoding.GetEncoding(1252)))
                        {
                            name = sr.ReadToEnd();
                        }
                        curBlockStream.Position = basePosition + 0x29;
                        int numBlocks = curBlockStream.ReadInt24LE();
                        curBlockStream.ReadInt24LE();
                        int           startBlock = curBlockStream.ReadInt24LE();
                        int           parentDir  = curBlockStream.ReadInt16BE();
                        uint          size       = curBlockStream.ReadUInt32BE();
                        int           update     = curBlockStream.ReadInt32BE();
                        int           access     = curBlockStream.ReadInt32BE();
                        STFSDirectory parent;
                        if (!dirsOrdinal.TryGetValue(parentDir, out parent)) // get the parent if it exists
                        {
                            throw new InvalidDataException("File references non-existent directory.");
                        }

                        if ((flags & 0x80) == 0x80)
                        {
                            // item is a directory
                            var tmp = new STFSDirectory(parent, name);
                            dirsOrdinal.Add(items, tmp);
                            parent.AddDir(tmp);
                        }
                        else
                        {
                            // item is a file
                            STFSFile tmp;
                            if ((flags & 0x40) == 0x40) // blocks are sequential
                            {
                                var dataBlocks = GetFileBlocks(startBlock, numBlocks, (flags & 0x40) == 0x40);
                                tmp = new STFSFile(name, size, dataBlocks, parent, this);
                            }
                            else // offload block calculation until we need it
                            {
                                tmp = new STFSFile(name, size, startBlock, numBlocks, parent, this);
                            }
                            parent.AddFile(tmp);
                        }
                        items++;
                    }
                }
            }
        }
Esempio n. 49
0
        public void CtorTest1()
        {
            using (StringReader reader = new StringReader(String.Empty))
                using (TextFieldParser t = new TextFieldParser(reader))
                {
                    Assert.AreEqual(string.Empty, t.ReadToEnd(), "#A1");
                }

            using (StringReader reader = new StringReader("abc"))
                using (TextFieldParser t = new TextFieldParser(reader))
                {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#A2");
                }

            using (MemoryStream reader = new System.IO.MemoryStream(Encoding.ASCII.GetBytes("abc")))
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.ASCII))
                {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#A3");
                }

            using (MemoryStream reader = new System.IO.MemoryStream(Encoding.ASCII.GetBytes("abc")))
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.Unicode))
                {
                    Assert.IsTrue("abc" != t.ReadToEnd(), "#A4");
                }


            using (MemoryStream reader = new System.IO.MemoryStream(Encoding.ASCII.GetBytes("abc")))
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.Unicode, true))
                {
                    Assert.IsTrue("abc" != t.ReadToEnd(), "#A5");
                }

            using (MemoryStream reader = new System.IO.MemoryStream(Encoding.Unicode.GetBytes("abc")))
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.ASCII, true))
                {
                    Assert.IsTrue("abc" != t.ReadToEnd(), "#A6");
                }

            // Unicode string with bom
            using (MemoryStream reader = new System.IO.MemoryStream(new byte [] { 0xFF, 0xFE, 0x61, 0, 0x62, 0, 0x63, 0 }))
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.ASCII, true))
                {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#A7");
                }

            // UTF8 string with bom
            using (MemoryStream reader = new System.IO.MemoryStream(new byte [] { 0xEF, 0xBB, 0xBF, 0x61, 0x62, 0x63 }))
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.ASCII, true))
                {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#A8");
                }


            try {
                using (StringReader reader = new StringReader("abc")) {
                    using (TextFieldParser t = new TextFieldParser(reader)) {
                        Assert.AreEqual("abc", t.ReadToEnd(), "#A9");
                    }
                    reader.ReadToEnd();
                }
                Assert.Fail("Excepted 'ObjectDisposedException'");
            } catch (ObjectDisposedException ex) {
                Helper.RemoveWarning(ex);
            } catch (Exception ex) {
                Helper.RemoveWarning(ex);
                Assert.Fail("Excepted 'ObjectDisposedException'");
            }

            using (MemoryStream reader = new System.IO.MemoryStream(new byte [] { 0xEF, 0xBB, 0xBF, 0x61, 0x62, 0x63 })) {
                using (TextFieldParser t = new TextFieldParser(reader, Encoding.UTF8, true, true)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#A10");
                }
                reader.ReadByte();
            }


            using (MemoryStream reader = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("abc")))
                using (TextFieldParser t = new TextFieldParser(reader)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#A11");
                }


            string tmpfile;

            tmpfile = System.IO.Path.GetTempFileName();
            try {
                Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText(tmpfile, "abc", false);

                using (TextFieldParser t = new TextFieldParser(tmpfile)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#B01");
                }
            } finally {
                System.IO.File.Delete(tmpfile);
            }

            tmpfile = System.IO.Path.GetTempFileName();
            try {
                Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText(tmpfile, "abc", false);

                using (TextFieldParser t = new TextFieldParser(tmpfile, Encoding.ASCII)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#B02");
                }
            } finally {
                System.IO.File.Delete(tmpfile);
            }

            tmpfile = System.IO.Path.GetTempFileName();
            try {
                Microsoft.VisualBasic.FileIO.FileSystem.WriteAllBytes(tmpfile, new byte [] { 0xFF, 0xFE, 0x61, 0, 0x62, 0, 0x63, 0 }, false);

                using (TextFieldParser t = new TextFieldParser(tmpfile, Encoding.Unicode)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#B03");
                }
            } finally {
                System.IO.File.Delete(tmpfile);
            }


            tmpfile = System.IO.Path.GetTempFileName();
            try {
                Microsoft.VisualBasic.FileIO.FileSystem.WriteAllBytes(tmpfile, new byte [] { 0xFF, 0xFE, 0x61, 0, 0x62, 0, 0x63, 0 }, false);

                using (TextFieldParser t = new TextFieldParser(tmpfile, Encoding.UTF8, true)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#B04");
                }
            } finally {
                System.IO.File.Delete(tmpfile);
            }


            tmpfile = System.IO.Path.GetTempFileName();
            try {
                Microsoft.VisualBasic.FileIO.FileSystem.WriteAllBytes(tmpfile, new byte [] { 0x61, 0x62, 0x63 }, false);

                using (TextFieldParser t = new TextFieldParser(tmpfile, Encoding.UTF8, false)) {
                    Assert.AreEqual("abc", t.ReadToEnd(), "#B04");
                }
            } finally {
                System.IO.File.Delete(tmpfile);
            }
        }
Esempio n. 50
0
 public int get()
 {
     return(stream.ReadByte());
 }
Esempio n. 51
0
        public void Split()
        {
            int 当前包索引    = 0;
            int 一个包索引    = 0;
            int 当前遍历数据长度 = 0;// 包长度相加
            int 流长度      = 0;
            int 当前包长度    = 0;

            byte[] pageLen = new byte[2];
            byte[] 当前包Bits = null;
            int    一个包长度   = 0;

            byte[] 剩余数据 = null;
            int    test = 0;

            if (!是否规则转化)
            {
                规则转化();
            }
            流长度 = (int)men.Length;
            do
            {
                men.Position = 当前包索引;
                test         = men.ReadByte();
                if (test != 240)
                {
                    TReturn(); return;
                }
                men.Position = 当前包索引 + 1;
                men.Read(pageLen, 0, 2);
                当前包长度        = System.BitConverter.ToInt16(pageLen, 0) + 3;
                当前包Bits      = new byte[当前包长度];
                men.Position = 当前包索引;
                men.Read(当前包Bits, 0, 当前包Bits.Length);
                test = 当前包Bits[当前包Bits.Length - 1];
                if (test != 254)
                {
                    TReturn(); return;
                }
                try
                {
                    _SplitData(当前包Bits);
                }
                catch
                {
                }
                test = 当前包Bits[当前包Bits.Length - 1];
                //Debug.Assert(test == 254);

                //if (test != 254)
                //{ byte[] data = men.ToArray(); }

                当前遍历数据长度 = 当前遍历数据长度 + 当前包长度;

                if ((流长度 - 当前遍历数据长度) > 3)
                {
                    一个包索引        = 当前包索引 + 当前包长度;
                    men.Position = 一个包索引;
                    test         = men.ReadByte();
                    //Debug.Assert(test == 240);
                    if (test != 240)
                    {
                        TReturn(); return;
                    }
                    men.Position = 一个包索引 + 1;
                    men.Read(pageLen, 0, 2);
                    一个包长度 = System.BitConverter.ToInt16(pageLen, 0) + 3;
                    当前包索引 = 一个包索引;
                }
            } while ((流长度 - 当前遍历数据长度) > 一个包长度);
            if ((流长度 - 当前遍历数据长度) > 0)
            {
                剩余数据 = new byte[流长度 - 当前遍历数据长度];

                men.Position = 当前包索引;
                men.Read(剩余数据, 0, 剩余数据.Length);
                if (剩余数据.Length == 8)
                {
                    if (剩余数据[0] == 240 && 剩余数据[7] == 254)
                    {
                        _SplitData(剩余数据);
                        return;
                    }
                }
                test = 剩余数据[0];
                //Debug.Assert(test == 240);
                if (test != 240)
                {
                    TReturn(); return;
                }
                men.SetLength(0);
                men.Write(剩余数据, 0, 剩余数据.Length);
            }
        }
Esempio n. 52
0
    void PreviewImage(object sender, EventArgs e)
    {
        if (loaded_bmp == null)
        {
            ShowErrorDialog("Cannot preview: No file is loaded.");
            return;
        }

        var    ms          = new System.IO.MemoryStream();
        Bitmap bmp_written = new Bitmap(loaded_bmp);

        // Read text
        byte[] data = enc.GetBytes(text_input.Buffer.Text);
        ms.Write(data, 0, data.Length);
        ms.WriteByte(0);
        data        = null;
        ms.Position = 0;

        // Encode stuff
        byte counter   = 0;
        int  character = ms.ReadByte();

        byte[] hash_bytes = new byte[2];
        GetNextHash(ref hash_bytes);
        character ^= hash_bytes[0];

        for (int y = num_yoffset.ValueAsInt; y < loaded_bmp.Height; ++y)
        {
            for (int x = num_xoffset.ValueAsInt; x < loaded_bmp.Width; ++x)
            {
                Color c = loaded_bmp.GetPixel(x, y);
                if (c.A == 0)
                {
                    continue;
                }

                int pr, pg, pb;

                pr          = (c.R & 0xFE) | (character & 1);
                character >>= 1;
                pg          = (c.G & 0xFE) | (character & 1);
                character >>= 1;
                pb          = (c.B & 0xFE) | ((pr ^ pg ^ hash_bytes[1]) & 1);

                loaded_bmp.SetPixel(x, y, Color.FromArgb(c.A, pr, pg, pb));
                // Mark image as written
                bmp_written.SetPixel(x, y, Color.FromArgb(c.A, c.R, c.B, 255 - c.G));

                counter += 2;
                if (counter == 8)
                {
                    int newchr = ms.ReadByte();
                    if (newchr == -1)                     // End of file
                    {
                        goto EXIT_LOOP;
                    }

                    GetNextHash(ref hash_bytes);
                    //ShowErrorDialog("hash: " + hash_bytes[0] + "\nchar: " + newchr);
                    character = newchr ^ hash_bytes[0];
                    counter   = 0;
                }
            }
        }

        if (counter != 0)
        {
            ShowErrorDialog("Cannot write entire message: "
                            + (ms.Length - ms.Position) + " leftover bytes.");
        }

EXIT_LOOP:
        ms.Close();
        ms = new System.IO.MemoryStream();
        bmp_written.Save(ms, format);
        ms.Position        = 0;
        img_encoded.Pixbuf = new Gdk.Pixbuf(ms)
        ;                //.ScaleSimple(img_encoded.Allocation.Width, img_encoded.Allocation.Width, Gdk.InterpType.Hyper);
    }