Read() public method

public Read ( ) : int
return int
Beispiel #1
0
        public ExexEntry(BinaryReader reader)
            : this()
        {
            auraId = reader.ReadUInt16();
            auraSlot = reader.ReadUInt16();

            particleColor = readColor(reader);
            reader.Read(data1, 0, data1.Length);

            outerGlowColor = readColor(reader);
            innerGlowColor = readColor(reader);
            reader.Read(data2, 0, data2.Length);

            smoke1Color = readColor(reader);
            smoke1Invert = reader.ReadByte() != COLOR_NOT_INVERTED;
            reader.Read(data3, 0, data3.Length);

            smoke2Color = readColor(reader);
            smoke2Invert = reader.ReadByte() != COLOR_NOT_INVERTED;
            reader.Read(data4, 0, data4.Length);

            boltsColor = readColor(reader);
            boltsInvert = reader.ReadByte() != COLOR_NOT_INVERTED;
            reader.Read(data5, 0, data5.Length);
        }
		private static string StreamToHexString(Stream stream)
		{
			byte[] buffer = new byte[4096];

			StringBuilder strB = new StringBuilder(4096);

			using (BinaryReader br = new BinaryReader(stream))
			{
				int byteRead = br.Read(buffer, 0, buffer.Length);

				while (byteRead > 0)
				{
					for (int i = 0; i < byteRead; i++)
					{
						if (strB.Length == 0)
							strB.Append("0X");

						strB.AppendFormat("{0:X2}", buffer[i]);
					}

					byteRead = br.Read(buffer, 0, buffer.Length);
				}
			}

			if (strB.Length == 0)
				strB.Append("NULL");

			return strB.ToString();
		}
Beispiel #3
0
        private void ValidateDisposedExceptions(BinaryReader binaryReader)
        {
            byte[] byteBuffer = new byte[10];
            char[] charBuffer = new char[10];

            Assert.Throws<ObjectDisposedException>(() => binaryReader.PeekChar());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(byteBuffer, 0, 1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(charBuffer, 0, 1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadBoolean());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadByte());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadBytes(1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadChar());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadChars(1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadDecimal());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadDouble());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt16());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt32());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt64());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadSByte());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadSingle());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadString());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt16());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt32());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt64());
        }
        // MEMO:
        // The purpose of using"IPAddress.NetworkToHostOrder()" method is changing endian from big endian to little endian.

        public static IEnumerable<byte[]> GetModuleFromSSHPublicKeyString(string pubKeySSHFormat)
        {
            if (string.IsNullOrEmpty(pubKeySSHFormat)) yield break;

            // Split each rows
            var pubKeyBodies = pubKeySSHFormat
                .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(row => row.Trim().Split(' ', '\t').Last());

            foreach (var pubKeyBody in pubKeyBodies)
            {
                var pubKeyBin = Convert.FromBase64String(pubKeyBody);
                using (var ms = new MemoryStream(pubKeyBin))
                using (var binReader = new BinaryReader(ms))
                {
                    // Get byte size of algorithm name.
                    var sizeOfAlgorithmName = IPAddress.NetworkToHostOrder(binReader.ReadInt32());
                    // Read and drop algorithm name (generally, this is "ssh-rsa" 7 bytes).
                    binReader.Read(new byte[sizeOfAlgorithmName], 0, sizeOfAlgorithmName);

                    // Get byte size of exponent.
                    var sizeOfExponent = IPAddress.NetworkToHostOrder(binReader.ReadInt32());
                    // Read and drop exponent.
                    binReader.Read(new byte[sizeOfExponent], 0, sizeOfExponent);

                    // Get byte size of module.
                    var sizeOfModule = IPAddress.NetworkToHostOrder(binReader.ReadInt32());
                    // Read module and return it.
                    var module = new byte[sizeOfModule];
                    binReader.Read(module, 0, sizeOfModule);
                    yield return module;
                }
            }
        }
Beispiel #5
0
        public static BitmapImage GetImageFromUrl(string url)
        {
            var image = new BitmapImage();
            int BytesToRead = 100;
            var responseStream = Network.GetStream(url);
            if (responseStream == null)
            {
                return null;
            }
            BinaryReader reader = new BinaryReader(responseStream);
            MemoryStream memoryStream = new MemoryStream();

            byte[] bytebuffer = new byte[BytesToRead];
            int bytesRead = reader.Read(bytebuffer, 0, BytesToRead);

            while (bytesRead > 0)
            {
                memoryStream.Write(bytebuffer, 0, bytesRead);
                bytesRead = reader.Read(bytebuffer, 0, BytesToRead);
            }

            image.BeginInit();
            memoryStream.Seek(0, SeekOrigin.Begin);

            image.StreamSource = memoryStream;
            image.EndInit();

            return image;
        }
Beispiel #6
0
        public static void LoadElf(string FileName, SPU spu, bool setProgramCounter)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(FileName));
            // GetElfHeader
            byte[] elfMagic = new byte[4];
            br.Read(elfMagic, 0, 4);
            if (elfMagic[0] != 0x7F ||
                elfMagic[0] != 0x7F ||
                elfMagic[0] != 0x7F ||
                elfMagic[0] != 0x7F)
            {
                MessageBox.Show("Elf Magic Wrong (" + FileName + ")");
                return;
            }
            br.BaseStream.Seek(0, SeekOrigin.Begin);
            byte[] eHDR = new byte[0x34];
            br.Read(eHDR, 0, eHDR.Length);
            uint phdr_offset = ConversionUtil.byteToUInt(eHDR, 0x1C);
            ushort n_phdrs = ConversionUtil.byteToUShort(eHDR, 0x2C);
            for (ushort i = 0; i < n_phdrs; i++)
            {
                int error = LoadElfPHDR(br, spu, phdr_offset, i);
                if (error == 1)
                    MessageBox.Show("Didn't Load phdr " + i + " of File " + FileName);
                else if (error == 2)
                    MessageBox.Show("Local Storage Overflow!");
            }

            if (setProgramCounter)
                spu.IP = ConversionUtil.byteToUInt(eHDR, 0x18);
            br.Close();
        }
Beispiel #7
0
        private void cryptBtn_Click(object sender, EventArgs e)
        {
            // Copy header
            byte[] header = new byte[54];
            List<Byte> body = new List<byte>();
            byte[] temp = new byte[1];

            using (BinaryReader sourceF = new BinaryReader(File.Open(this.selFileTb.Text, FileMode.Open)))
            {
                sourceF.Read(header, 0, header.Length);
                using (BinaryWriter newF = new BinaryWriter(File.Open(this.newFileTb.Text, FileMode.OpenOrCreate)))
                {
                    newF.Write(header, 0, header.Length);
                    int len = 0;
                    while (sourceF.BaseStream.Position != sourceF.BaseStream.Length)
                    {
                        sourceF.Read(temp, 0, 1);
                        body.Add(temp[0]);
                        len++;
                    }
                    byte[] b = body.ToArray();

                    newF.Write(this.Crypt(b), 0, len);
                }
            }
        }
        public static List<DATFile> FindFiles(DAT dat, BinaryReader br)
        {
            List<DATFile> DatFiles = new List<DATFile>();

            uint FileIndex = 0;
            br.BaseStream.Seek(-(dat.TreeSize + 4), SeekOrigin.End);
            while (FileIndex < dat.FilesTotal)
            {
                DATFile file = new DATFile();
                file.br = br;
                file.FileNameSize = br.ReadInt32();
                char[] namebuf = new Char[file.FileNameSize];
                br.Read(namebuf, 0, (int)file.FileNameSize);
                file.Path = new String(namebuf, 0, namebuf.Length);
                file.FileName = Path.GetFileName(file.Path);
                file.Compression = br.ReadByte();
                file.UnpackedSize = br.ReadInt32();
                file.PackedSize = br.ReadInt32();
                if (file.Compression==0x00&&(file.UnpackedSize != file.PackedSize))
                        file.Compression = 1;
                file.Offset = br.ReadInt32();
                long oldoffset = br.BaseStream.Position;
                // Read whole file into a buffer
                br.BaseStream.Position = file.Offset;
                file.Buffer = new Byte[file.PackedSize];
                br.Read(file.Buffer, 0, file.PackedSize);
                br.BaseStream.Position = oldoffset;

                DatFiles.Add(file);
                FileIndex++;
            }
            return DatFiles;
        }
 public void ParseInfo(long pos, string filePath)
 {
     byte[] array = new byte[100000];
     BinaryReader binaryReader = new BinaryReader(File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read));
     try
     {
         binaryReader.BaseStream.Position = pos + VolumePathOffset;
         binaryReader.Read(array, 0, VolumePathLength*2);
         string name = Encoding.Unicode.GetString(array).TrimEnd('\0'); //bytestostring_littleendian(array);
         binaryReader.BaseStream.Position = pos + FolderPathOffset;
         List<string> iFolderPaths = new List<string>();
         for (int i = 0; i < NumFolderPaths; i++)
         {
             byte[] array2 = new byte[100000];
             binaryReader.Read(array2, 0, 2);
             uint len = BitConverter.ToUInt16(array2, 0);
             binaryReader.Read(array2, 0, (int)len*2);
             string szPath = Encoding.Unicode.GetString(array2).TrimEnd('\0');
             if (szPath != "")
                 iFolderPaths.Add(szPath);
             binaryReader.Read(array2, 0, 2);
         }
         FolderPaths = iFolderPaths.ToArray();
     }
     finally
     {
         binaryReader.Close();
     }
 }
Beispiel #10
0
        public IEnumerable<FileEntry> ListFiles(Stream strm, Callbacks callbacks)
        {
            byte[] buf = new byte[4];
            BinaryReader rd = new BinaryReader(strm);
            int numFiles;
            List<FileEntry> results = new List<FileEntry>();

            rd.Read(buf, 0, 4);
            if (Encoding.ASCII.GetString(buf, 0, 4) != "TGP0")
                return results;

            if (rd.ReadInt32() != 1)  // version check
                return results;

            if (rd.ReadInt32() != 0)  // should be zero
                return results;

            numFiles = rd.ReadInt32();
            buf = new byte[0x60];
            for (int i = 0; i < numFiles; i++)
            {
                FileEntry ent = new FileEntry();

                rd.Read(buf, 0, 0x60);
                ent.Filename = Encoding.ASCII.GetString(buf);
                ent.Filename = ent.Filename.Substring(0, ent.Filename.IndexOf('\0'));
                ent.Offset = rd.ReadInt64();
                ent.UncompressedSize = rd.ReadInt64();

                results.Add(ent);
            }

            return results;
        }
Beispiel #11
0
        protected BitmapImage icon(string url)
        {
            var image = new BitmapImage();
            int BytesToRead = 100;

            WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));
            request.Timeout = -1;
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            BinaryReader reader = new BinaryReader(responseStream);
            MemoryStream memoryStream = new MemoryStream();

            byte[] bytebuffer = new byte[BytesToRead];
            int bytesRead = reader.Read(bytebuffer, 0, BytesToRead);

            while (bytesRead > 0)
            {
                memoryStream.Write(bytebuffer, 0, bytesRead);
                bytesRead = reader.Read(bytebuffer, 0, BytesToRead);
            }

            image.BeginInit();
            memoryStream.Seek(0, SeekOrigin.Begin);

            image.StreamSource = memoryStream;
            image.EndInit();
            return image;
        }
        private void CreateSettingsFile()
        {
            Assembly assembly = GetType().Assembly;
            BinaryReader reader = new BinaryReader(assembly.GetManifestResourceStream("D3.Commission.Settings.xml"));
            FileStream stream = new FileStream(FilePath, FileMode.Create);
            BinaryWriter writer = new BinaryWriter(stream);
            try
            {
                byte[] buffer = new byte[64 * 1024];
                int numread = reader.Read(buffer, 0, buffer.Length);

                while (numread > 0)
                {
                    writer.Write(buffer, 0, numread);
                    numread = reader.Read(buffer, 0, buffer.Length);
                }

                writer.Flush();
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Beispiel #13
0
        public ObjectEntry(BinaryReader reader)
            : this()
        {
            id = reader.ReadUInt16();
            data1 = reader.ReadUInt16();
            data2 = reader.ReadUInt16();
            characterId = reader.ReadByte();
            costumeId = reader.ReadByte();
            objectEntryType = reader.ReadByte();
            objectEntrySlot = reader.ReadByte();

            for (int i = 0; i < MODEL_DATA_BYTES; i++)
            {
                modelData[i] = reader.ReadByte();
            }

            for (int i = 0; i < ATTACHMENT_IDS_ARRAY_SIZE; i++)
            {
                attachmentIds[i] = reader.ReadUInt16();
            }
            byte[] buffer = new byte[16];
            reader.Read(buffer, 0, 16);
            modelName = Encoding.ASCII.GetString(buffer).TrimEnd('\0');

            buffer = new byte[16];
            reader.Read(buffer, 0, 16);
            objxName = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
        }
        private static BitmapImage GetImageFromUrl(string url)
        {
            var image = new BitmapImage();
            const int bytesToRead = 100;
            var request =
                WebRequest.Create(
                    new Uri(url, UriKind.Absolute));
            request.Timeout = -1;
            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            if (responseStream != null)
            {
                var reader = new BinaryReader(responseStream);
                var memoryStream = new MemoryStream();

                var bytebuffer = new byte[bytesToRead];
                var bytesRead = reader.Read(bytebuffer, 0, bytesToRead);

                while (bytesRead > 0)
                {
                    memoryStream.Write(bytebuffer, 0, bytesRead);
                    bytesRead = reader.Read(bytebuffer, 0, bytesToRead);
                }

                image.BeginInit();
                memoryStream.Seek(0, SeekOrigin.Begin);

                image.StreamSource = memoryStream;
            }
            image.EndInit();
            return image;
        }
        public void Read(Stream stream)
        {
            BinaryReader reader = new BinaryReader (stream);
                int headerSize = IPAddress.NetworkToHostOrder(reader.ReadInt32());
                int keySize = IPAddress.NetworkToHostOrder(reader.ReadInt32());
                int valueSize = IPAddress.NetworkToHostOrder(reader.ReadInt32());
                int packetVersion = reader.ReadByte();
                if (packetVersion != PACKET_VERSION)
                {
                    //throw new Exception("Packet versions do not match. Expected " + PACKET_VERSION + " but found " + packetVersion);
                }
                readHeader(reader);

                try
                {
                    this.key = new byte[keySize];
                    if (keySize > 0)
                        reader.Read(this.key, 0, keySize);
                    this.value = new byte[valueSize];
                    if (valueSize > 0)
                    {
                        int x = reader.Read(this.value, 0, valueSize);
                        if (x != valueSize) {
                            Console.WriteLine("Esit degil: " + x + "::" + valueSize + "");
                            Thread.Sleep(10000);
                        }
                    }
                }catch (Exception e) {
                    Console.WriteLine("Keysize" + keySize + ": " + valueSize);
                    Console.WriteLine(e.StackTrace);
                }
        }
Beispiel #16
0
 public void Close()
 {
     if (writer == null)
         return;
     writer.Close();
     writer = null;
     using (BinaryWriter bw2 = new BinaryWriter(wavR.OpenResourceForWrite()))
     {
         bw2.Write((Int32)1179011410);
         bw2.Write((Int32)44 + length - 8);
         bw2.Write((Int32)1163280727);
         bw2.Write((Int32)544501094);
         bw2.Write((Int32)16);
         bw2.Write((Int16)1);
         bw2.Write((Int16)channels);
         bw2.Write((Int32)sRate);
         bw2.Write((Int32)(sRate * channels * (bits / 8)));
         bw2.Write((Int16)(channels * (bits / 8)));
         bw2.Write((Int16)bits);
         bw2.Write((Int32)1635017060);
         bw2.Write((Int32)length);
         using (BinaryReader br = new BinaryReader(tempR.OpenResourceForRead()))
         {
             byte[] buffer = new byte[1024];
             int count = br.Read(buffer, 0, buffer.Length);
             while (count > 0)
             {
                 bw2.Write(buffer, 0, count);
                 count = br.Read(buffer, 0, buffer.Length);
             }
         }
     }
     tempR.DeleteResource();
 }
        public void Should_Read_Boolean_Value()
        {
            var reader = new BinaryReader(new MemoryStream(new byte[] {1, 0}));
            var value = reader.Read(DataType.Boolean);
            value.ShouldBeType<bool>();
            ((bool)value).ShouldBeTrue();

            reader.Read<bool>(DataType.Boolean).ShouldBeFalse();
        }
Beispiel #18
0
 /// <summary>
 /// Load board state
 /// </summary>
 /// <param name="stream">The stream that should be used to read data</param>
 public virtual void LoadState(System.IO.BinaryReader stream)
 {
     // Read prg ram
     for (int i = 0; i < prg_banks.Length; i++)
     {
         if (prg_isram[i])
         {
             stream.Read(prg_banks[i], 0, prg_banks[i].Length);
         }
     }
     // Write prg indexes, enable ...etc
     for (int i = 0; i < prg_indexes.Length; i++)
     {
         prg_indexes[i] = stream.ReadInt32();
     }
     for (int i = 0; i < prg_enable.Length; i++)
     {
         prg_enable[i] = stream.ReadBoolean();
     }
     for (int i = 0; i < prg_writable.Length; i++)
     {
         prg_writable[i] = stream.ReadBoolean();
     }
     // Write chr ram
     for (int i = 0; i < chr_banks.Length; i++)
     {
         if (chr_isram[i])
         {
             stream.Read(chr_banks[i], 0, chr_banks[i].Length);
         }
     }
     // Write chr indexes, enable ...etc
     for (int i = 0; i < chr_indexes.Length; i++)
     {
         chr_indexes[i] = stream.ReadInt32();
     }
     for (int i = 0; i < chr_enable.Length; i++)
     {
         chr_enable[i] = stream.ReadBoolean();
     }
     for (int i = 0; i < chr_writable.Length; i++)
     {
         chr_writable[i] = stream.ReadBoolean();
     }
     // Write nmt
     for (int i = 0; i < nmt_banks.Length; i++)
     {
         stream.Read(nmt_banks[i], 0, nmt_banks[i].Length);
     }
     // Write chr indexes, enable ...etc
     for (int i = 0; i < nmt_indexes.Length; i++)
     {
         nmt_indexes[i] = stream.ReadInt32();
     }
 }
        public void Should_Read_Float_Value()
        {
            var reader = new BinaryReader(new MemoryStream(new byte[] { 174, 71, 1, 192, 174, 71, 129, 191, 0, 0, 0, 0,
                                                                        174, 71, 129, 63, 174, 71, 1, 64 }));
            var value = reader.Read(DataType.SingleFloat);
            value.ShouldBeType<float>();
            ((float)value).ShouldEqual(-2.02f);

            reader.Read<float>(DataType.SingleFloat).ShouldEqual(-1.01f);
            reader.Read<float>(DataType.SingleFloat).ShouldEqual(0.00f);
            reader.Read<float>(DataType.SingleFloat).ShouldEqual(1.01f);
            reader.Read<float>(DataType.SingleFloat).ShouldEqual(2.02f);
        }
Beispiel #20
0
        /// <summary>This method creates a picture object from the contents
        /// of the passed in bitmap file.</summary>
        /// <remark>Note: The bitmap file is embedded as a resource in the 
        /// executable. The file is temporarily copied out to the client 
        /// file system by this function, since the OleLoadPictureFile 
        /// function requires the file to reside in the file system.</remark>
        ///	<param name="resourceName">File name of the bitmap embedded as
        /// a resource in the executable</param>
        /// <returns>stdole.IPictureDisp object created from the contents 
        /// of the file.</returns>
        public static IPictureDisp GetPicture( string resourceName )
        {
            int loadPictureResult;
            Object picture = null;

            try
            {
                string temporaryFile = Path.GetTempFileName();

                // Get an input stream of the bitmap file embedded
                // in the executable.
                Stream inStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( BasePath + resourceName );

                // Create a BinaryReader from the input stream.
                BinaryReader inReader = new BinaryReader( inStream );

                // Create the output stream for the temporary file.
                FileStream outStream = new FileStream( temporaryFile, FileMode.Create );

                // Create a BinaryWriter from the output stream.
                BinaryWriter outWriter = new BinaryWriter( outStream );

                byte[] buffer = new byte[ 1000 ];
                int bytesRead = inReader.Read( buffer, 0, buffer.Length );

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

                inReader.Close();
                outWriter.Close();

                // Load the bitmap from the temporary file.
                loadPictureResult = OleLoadPictureFile( temporaryFile, out picture );

                // Delete the temporary file.
                File.Delete( temporaryFile );

                if ( loadPictureResult != 0 )
                    throw new COMException( "OleLoadPictureFailed", loadPictureResult );
            }
            catch ( COMException ex )
            {
                ESIMessageBox.ShowError(ex);
            }

            return (IPictureDisp) picture;
        }
        public void Should_Read_Double_With_Unit_Value()
        {
            var reader = new BinaryReader(new MemoryStream(new byte[] { 41, 92, 143, 194, 245, 40, 0, 192, 41, 92, 143, 194,
                                                                        245, 40, 240, 191, 0, 0, 0, 0, 0, 0, 0, 0, 41, 92,
                                                                        143, 194, 245, 40, 240, 63, 41, 92, 143, 194, 245,
                                                                        40, 0, 64 }));
            var value = reader.Read(DataType.DoubleFloatWithUnit);
            value.ShouldBeType<double>();
            ((double)value).ShouldEqual(-2.02);

            reader.Read<double>(DataType.DoubleFloatWithUnit).ShouldEqual(-1.01);
            reader.Read<double>(DataType.DoubleFloatWithUnit).ShouldEqual(0);
            reader.Read<double>(DataType.DoubleFloatWithUnit).ShouldEqual(1.01);
            reader.Read<double>(DataType.DoubleFloatWithUnit).ShouldEqual(2.02);
        }
Beispiel #22
0
        private static byte[] ReadBeginningAndEnd(Stream stream)
        {
            if (stream.Length < BlockSize)
                return new byte[0];

            using (var binaryReader = new BinaryReader(stream))
            {
                var buffer = new byte[BlockSize * 2];
                binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);
                binaryReader.Read(buffer, 0, BlockSize);
                binaryReader.BaseStream.Seek(-BlockSize, SeekOrigin.End);
                binaryReader.Read(buffer, BlockSize, BlockSize);
                return buffer;
            }
        }
 internal void ReadExtraData(BinaryReader reader)
 {
     if (this.extraSize > 0)
     {
         reader.Read(extraData, 0, extraSize);
     }
 }
        /// <summary>
        /// Reads the response data into ResponseInfo.ResponseBytes
        /// </summary>
        /// <param name="resp">HttpWebResponse object</param>
        private void ReadResponse(HttpWebResponse resp)
        {
            int bufSizeChunk = 30000;
            int totalBufSize = bufSizeChunk;

            byte[] fileBytes = new byte[totalBufSize];

            int totalBytesRead = 0;

            using (var reader = new System.IO.BinaryReader(resp.GetResponseStream()))
            {
                // ContentLength is not set, so realloc as needed to compensate
                int bytesRead = 0;

                while ((bytesRead = reader.Read(fileBytes, totalBytesRead, totalBufSize - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if ((totalBufSize - totalBytesRead) == 0)
                    {
                        totalBufSize += bufSizeChunk;
                        Array.Resize(ref fileBytes, totalBufSize);
                    }
                }

                Array.Resize(ref fileBytes, totalBytesRead);
                this.responseInfo.ResponseBytes = fileBytes;
            }
        }
        /// <summary>
        /// 保存上传文件到磁盘目录(此方法在http_service_handler的Upload中在文件类型校验合法后被调用)
        /// </summary>
        /// <param name="param">上传参数配置</param>
        /// <param name="fileHash">上传文件的物理路径Hashtable</param>
        internal static void SaveToDisk(UploadParameter param, System.Collections.Hashtable fileHash)
        {
            int cur_build = 0;      // 创建文件保存路径次数            
            string _filePath = string.Empty;

            if (!Directory.Exists(param.SaveToDir))
            {
                if (!param.AutoMKDir)
                    throw new APIFW_ArgumentException(" 上传目录不存在,请手动创建目录或将AutoMKDir参数设置为True ");
                fileHash.Add(-1, Directory.CreateDirectory(param.SaveToDir).FullName);
            }

            int size = 0;
            long completed = 0;
            byte[] buffer = new byte[param.BufferSize];

            for (int i = 0; i < param.FileUploads.Length; i++)
            {
                cur_build = 0;      // 上传文件名称重命名计数
                completed = 0;      // 当前上传文件已保存大小

                AdjustUploadItemFileName(param, ref param.FileUploads[i], ref cur_build, ref _filePath);

                if (param.FileUploads[i].IsValid && param.FileUploads[i].FileName != null &&
                    param.FileUploads[i].ContentLength > 0 && param.FileUploads[i].FileName.Length > 0)
                {
                    try
                    {
                        // 开始上传
                        param.ExcuteOnUploadItemStart(param.FileUploads[i]);

                        // request.Files.Get(param.FileUploads[i].ClientKey).SaveAs(_filePath);
                        using (FileStream fs = new FileStream(_filePath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            using (BinaryWriter bw = new BinaryWriter(fs))
                            {
                                using (BinaryReader br = new BinaryReader(param.FileUploads[i].InputStream))
                                {
                                    while ((size = br.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        completed += size;
                                        bw.Write(buffer, 0, size);

                                        // 进度变化
                                        param.ExcuteOnUploadItemProgressChange(param.FileUploads[i], completed);
                                    }
                                }
                            }
                        }
                        // 上传完成
                        param.ExcuteOnUploadItemCompleted(param.FileUploads[i]);
                    }
                    catch (Exception ex)
                    {
                        // 上传出错
                        if (!param.ExcuteOnUploadItemFailedHandler(param.FileUploads[i], ex)) { throw ex; }
                    }
                }
            }
        }
        public static ConnectionSettings Read(byte[] data)
        {
            var cs = new ConnectionSettings();
            using (var ms = new MemoryStream(data))
            using (var br = new BinaryReader(ms))
            {
                cs.Version = br.ReadInt32();
                cs.Counter = br.ReadInt32();
                cs.Autodetect = (Autodetect)br.ReadInt32();

                var len = br.ReadInt32();
                cs.ProxyServer = Utf8.GetString(br.ReadBytes(len));

                len = br.ReadInt32();
                cs.ExtraData = Utf8.GetString(br.ReadBytes(len));

                len = br.ReadInt32();
                cs.AutodetectScript = Utf8.GetString(br.ReadBytes(len));

                // So damn lazy.
                using (var ms2 = new MemoryStream())
                {
                    var ba = new byte[Environment.SystemPageSize];
                    while ((len = br.Read(ba, 0, ba.Length)) != 0)
                    {
                        ms2.Write(ba, 0, len);
                    }

                    cs.Junk = ms2.ToArray();
                }
            }

            return cs;
        }
Beispiel #27
0
        private void Load(BinaryReader br)
        {
            int length = br.ReadByte();

            if (this.Type == EventType.SystemExclusiveF0)
            {
                this.Data = new byte[length + 1];
                this.Data[0] = 0xf0;
                br.Read(this.Data, 1, length);
            }
            else
            {
                this.Data = new byte[length];
                br.Read(this.Data, 0, length);
            }
        }
Beispiel #28
0
 private bool FileCopy(string srcfilename, string destfilename)
 {
     if (System.IO.File.Exists(srcfilename) == false)
     {
         return(false);
     }
     System.IO.Stream       s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     System.IO.Stream       s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create, FileAccess.ReadWrite, FileShare.Delete);
     System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1);
     System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2);
     while (true)
     {
         byte[] buf = new byte[10240];
         int    sz  = f1.Read(buf, 0, 10240);
         if (sz <= 0)
         {
             break;
         }
         f2.Write(buf, 0, sz);
         if (sz < 10240)
         {
             break;
         }
     }
     f1.Close();
     f2.Close();
     return(true);
 }
        public static void CopyFileBinary(string srcfilename, string destfilename)
        {
            System.IO.Stream       s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open);
            System.IO.Stream       s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create);
            System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1);
            System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2);

            while (true)
            {
                byte[] buf = new byte[1024];
                int    sz  = f1.Read(buf, 0, 1024);
                if (sz <= 0)
                {
                    break;
                }

                f2.Write(buf, 0, sz);
                if (sz < 10240)
                {
                    break; // eof reached
                }
            }

            f1.Close();
            f2.Close();
        }
 public void WriteFontToStream(string fontPath, Stream outputStream)
 {
     lock (_accesslock)
     {
         int iCount;
         var buffer = new Byte[2048];
         if (!_cachedFonts.ContainsKey(fontPath))
         {
             var tempStream = new MemoryStream();
             using (var reader = new BinaryReader(File.OpenRead(fontPath)))
             {
                 while ((iCount = reader.Read(buffer, 0, 2048)) != 0)
                 {
                     tempStream.Write(buffer, 0, iCount);
                 }
             }
             _cachedFonts.Add(fontPath,tempStream);
         }
         MemoryStream fontStream = _cachedFonts[fontPath];
         fontStream.Seek(0, SeekOrigin.Begin);
         while ((iCount = fontStream.Read(buffer, 0, 2048)) != 0)
         {
             outputStream.Write(buffer,0, iCount);
         }
         
     }
 }
		/// <summary>
		/// Decompressed the data in the given stream.
		/// </summary>
		/// <param name="br">The stream containing the compressed data.</param>
		/// <param name="size">The number of byte to decompress.</param>
		/// <param name="outsize">The sixe of the decrompressed data.</param>
		/// <returns>A reader for the uncompressed data.</returns>
		protected static BinaryReader Decompress(BinaryReader br, int size, int outsize)
		{
			if (input.Length < size)
			{
				input = new byte[size];
			}
			if (output.Length < outsize)
			{
				output = new byte[outsize];
			}
			br.Read(input, 0, size);

			inf.SetInput(input, 0, size);
			try
			{
				inf.Inflate(output);
			}
			catch (ICSharpCode.SharpZipLib.SharpZipBaseException e)
			{
				//we ignore adler checksum mismatches, as I have a notion that they aren't always correctly
				// stored in the records.
				if (!e.Message.StartsWith("Adler"))
					throw e;
			}
			inf.Reset();

			ms.Position = 0;
			ms.Write(output, 0, outsize);
			ms.Position = 0;

			return compReader;
		}
 private void downloadShapefileThreadMethod()
 {
     try
     {
         //download zip file
         using (TemporaryFile tmpFile = new TemporaryFile(false))
         {
             using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_plugin, STR_DOWNLOADINGSHAPEFILE, _downloadUrl, _zipFileSize, 0))
             {
                 byte[]         buffer    = new byte[20 * 1024];
                 int            totalRead = 0;
                 HttpWebRequest wr        = (HttpWebRequest)HttpWebRequest.Create(_downloadUrl);
                 using (System.IO.BinaryReader sr = new System.IO.BinaryReader(wr.GetResponse().GetResponseStream()))
                     using (FileStream fs = File.OpenWrite(tmpFile.Path))
                     {
                         while (totalRead < _zipFileSize)
                         {
                             int bytesRead = sr.Read(buffer, 0, buffer.Length);
                             if (bytesRead > 0)
                             {
                                 fs.Write(buffer, 0, bytesRead);
                             }
                             totalRead += bytesRead;
                             prog.UpdateProgress(STR_DOWNLOADINGSHAPEFILE, _downloadUrl, _zipFileSize, totalRead);
                         }
                     }
             }
             UnZipFiles(tmpFile.Path, PluginSettings.Instance.DefaultShapeFilesFolder, false);
         }
     }
     catch
     {
         _error = true;
     }
 }
Beispiel #33
0
        public WebImage(Stream imageStream) {
            if (imageStream.CanSeek) {
                imageStream.Seek(0, SeekOrigin.Begin);

                _content = new byte[imageStream.Length];
                using (BinaryReader reader = new BinaryReader(imageStream)) {
                    reader.Read(_content, 0, (int)imageStream.Length);
                }
            }
            else {
                List<byte[]> chunks = new List<byte[]>();
                int totalSize = 0;
                using (BinaryReader reader = new BinaryReader(imageStream)) {
                    // Pick some size for chunks that is still under limit
                    // that causes them to be placed on the large object heap.
                    int chunkSizeInBytes = 1024 * 50;
                    byte[] nextChunk = null;
                    do {
                        nextChunk = reader.ReadBytes(chunkSizeInBytes);
                        totalSize += nextChunk.Length;
                        chunks.Add(nextChunk);
                    }
                    while (nextChunk.Length == chunkSizeInBytes);
                }

                _content = new byte[totalSize];
                int startIndex = 0;
                foreach (var chunk in chunks) {
                    chunk.CopyTo(_content, startIndex);
                    startIndex += chunk.Length;
                }
            }
            _initialFormat = ValidateImageContent(_content, "imageStream");
            _currentFormat = _initialFormat;
        }
Beispiel #34
0
        /// <inheritdoc></inheritdoc>
        public override void ReadHeader()
        {
            byte[] header = new byte[176];
            using (Stream str = GetStream())
            {
                if (str == null) return;
                // Read important header content
                using (BinaryReader br = new BinaryReader(str))
                {
                    br.Read(header, 0, 176);
                }
            }

            PhiLam ll;
            ll.Phi = GetDouble(header, 24);
            ll.Lambda = -GetDouble(header, 72);

            double urPhi = GetDouble(header, 40);
            double urLam = -GetDouble(header, 56);

            PhiLam cs = new PhiLam();
            cs.Phi = GetDouble(header, 88);
            cs.Lambda = GetDouble(header, 104);

            NumLambdas = (int)(Math.Abs(urLam - ll.Lambda) / cs.Lambda + .5) + 1;
            NumPhis = (int)(Math.Abs(urPhi - ll.Phi) / cs.Phi + .5) + 1;
            ll.Lambda *= DEG_TO_RAD;
            ll.Phi *= DEG_TO_RAD;
            cs.Lambda *= DEG_TO_RAD;
            cs.Phi *= DEG_TO_RAD;

            LowerLeft = ll;
            CellSize = cs;
        }
        public static void Convert(string icofile)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream(icofile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read));
            NewHeader nh = new NewHeader();

            nh.Read(br);
            ResDir[] rd = new ResDir[nh.ResCount];
            for (int i = 0; i < nh.ResCount; i++)
            {
                rd[i].Read(br);
            }
            byte[] bits = new byte[0];
            for (int i = 0; i < nh.ResCount; i++)
            {
                br.BaseStream.Seek(rd[i].Offset, System.IO.SeekOrigin.Begin);
                if (bits.Length < rd[i].BytesInRes)
                {
                    bits = new byte[rd[i].BytesInRes];
                }
                br.Read(bits, 0, rd[i].BytesInRes);
                int bitcount, width, height;
                System.Drawing.Bitmap bm = Decode(bits, 0, rd[i].BytesInRes, out width, out height, out bitcount);
                string fileName          = string.Format("{0}-{1}x{2}-{3}bpp.png", System.IO.Path.GetFileNameWithoutExtension(icofile), width, height, bitcount);
                bm.Save(fileName);
                bm.Dispose();
                Console.WriteLine(string.Format("  Saved {0}", fileName));
            }
            br.Close();
        }
 public void Read(System.IO.BinaryReader br)
 {
     this.Size          = br.ReadInt32();
     this.Width         = br.ReadInt32();
     this.Height        = br.ReadInt32();
     this.Planes        = br.ReadInt16();
     this.BitCount      = br.ReadInt16();
     this.Compression   = br.ReadInt32();
     this.SizeImage     = br.ReadInt32();
     this.XPelsPerMeter = br.ReadInt32();
     this.YPelsPerMeter = br.ReadInt32();
     this.ClrUsed       = br.ReadInt32();
     this.ClrImportant  = br.ReadInt32();
     if ((this.ClrUsed > 0) || (this.BitCount < 16))
     {
         int colors = 0;
         if (this.BitCount < 16)
         {
             colors = 1 << this.BitCount;
         }
         else
         {
             colors = this.ClrUsed;
         }
         this.Colors = new int[colors];
         byte[] buf = new byte[4 * colors];
         br.Read(buf, 0, buf.Length);
         System.Buffer.BlockCopy(buf, 0, this.Colors, 0, buf.Length);
     }
     else
     {
         this.Colors = new int[0];
     }
 }
Beispiel #37
0
        public static void CopyFromResourceToPhone()
        {
            if (File.Exists(Constants.DatabasePath))
            {
                //File.Delete(Constants.DatabasePath);
                return;
            }

            var manager = new ResourceManager("SheardResources.Properties.Resources", typeof(SheardResClass).Assembly);

            using (var stream = new MemoryStream(manager.GetObject("QuranAlkarim") as byte[]))
            {
                using (var reader = new System.IO.BinaryReader(stream))
                {
                    using (BinaryWriter bw = new BinaryWriter(new FileStream(Constants.DatabasePath, FileMode.CreateNew)))
                    {
                        byte[] buffer = new byte[1024];
                        int    len    = 0;
                        while ((len = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            bw.Write(buffer, 0, len);
                        }
                    }
                }
            }
        }
 public void CopyDatabase()
 {
     if (!File.Exists(dbPath)) //-------------------------------------------------------------------------Check if file exists
     {
         using (BinaryReader br = new BinaryReader(Assets.Open(dbName))) //-------------------------------if not opens database
         {
             try
             {
                 using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create))) //---writes file to phone
                 {
                     byte[] buffer = new byte[2048];
                     int len = 0;
                     while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
                     {
                         bw.Write(buffer, 0, len);
                     }
                 }
             }
             catch (Exception e)
             {
                 Console.WriteLine("{0} Exception caught.", e); //----------------------------------------write error to output
             }
         }
     }
 }
Beispiel #39
0
        /// <summary>
        /// 分析网络数据包并进行转换为信息对象
        /// </summary>
        /// <param name="packs">接收到的封包对象</param>
        /// <returns></returns>
        /// <remarks>
        /// 对于分包消息,如果收到的只是片段并且尚未接收完全,则不会进行解析
        /// </remarks>
        public static IPMessager.Entity.Message ParseToMessage(params Entity.PackedNetworkMessage[] packs)
        {
            if (packs.Length == 0 || (packs[0].PackageCount > 1 && packs.Length != packs[0].PackageCount))
            {
                return(null);
            }

            var ms = DecompressMessagePacks(packs);

            if (ms == null)
            {
                OnDecompressFailed(new DecomprssFailedEventArgs(packs));
                return(null);
            }

            //构造读取流
            var br = new System.IO.BinaryReader(ms, System.Text.Encoding.Unicode);

            //开始读出数据
            var m = new FSLib.IPMessager.Entity.Message(packs[0].RemoteIP);

            m.PackageNo = br.ReadUInt64();                                                      //包编号
            var tl = br.ReadUInt64();

            m.Command = (Define.Consts.Commands)(tl & 0xFF); //命令编码
            m.Options = tl & 0xFFFFFF00;                     //命令参数

            m.UserName = br.ReadString();                    //用户名
            m.HostName = br.ReadString();                    //主机名

            var length = br.ReadInt32();

            m.NormalMsgBytes = new byte[length];
            br.Read(m.NormalMsgBytes, 0, length);

            length = br.ReadInt32();
            m.ExtendMessageBytes = new byte[length];
            br.Read(m.ExtendMessageBytes, 0, length);

            if (!Consts.Check(m.Options, Consts.Cmd_All_Option.BinaryMessage))
            {
                m.NormalMsg     = System.Text.Encoding.Unicode.GetString(m.NormalMsgBytes, 0, length);                  //正文
                m.ExtendMessage = System.Text.Encoding.Unicode.GetString(m.ExtendMessageBytes, 0, length);              //扩展消息
            }

            return(m);
        }
Beispiel #40
0
        /// <summary>
        /// //Get MNIST Image file'header
        /// </summary>
        protected bool MnistImageFileHeader()
        {
            if (_bImageFileOpen == false)
            {
                byte[] m_byte          = new byte[4];
                var    openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
                openFileDialog1.Filter = "Mnist Image file (*.idx3-ubyte)|*.idx3-ubyte";
                openFileDialog1.Title  = "Open Minist Image File";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    _MnistImageFileName = openFileDialog1.FileName;

                    try
                    {
                        load_ImageFile_stream = new System.IO.BinaryReader(openFileDialog1.OpenFile());
                        //Magic number
                        load_ImageFile_stream.Read(m_byte, 0, 4);
                        Array.Reverse(m_byte, 0, 4);
                        _ImageFileBegin.nMagic = BitConverter.ToInt32(m_byte, 0);
                        //number of images
                        load_ImageFile_stream.Read(m_byte, 0, 4);
                        //High-Endian format to Low-Endian format
                        Array.Reverse(m_byte, 0, 4);
                        _ImageFileBegin.nItems = BitConverter.ToInt32(m_byte, 0);
                        _nItems = (uint)_ImageFileBegin.nItems;
                        //number of rows
                        load_ImageFile_stream.Read(m_byte, 0, 4);
                        Array.Reverse(m_byte, 0, 4);
                        _ImageFileBegin.nRows = BitConverter.ToInt32(m_byte, 0);
                        //number of columns
                        load_ImageFile_stream.Read(m_byte, 0, 4);
                        Array.Reverse(m_byte, 0, 4);
                        _ImageFileBegin.nCols = BitConverter.ToInt32(m_byte, 0);
                        _bImageFileOpen       = true;
                        return(true);
                    }
                    catch
                    {
                        _bImageFileOpen = false;
                        return(false);
                    }
                }
                return(false);
            }
            return(true);
        }
 /// <summary>
 /// Reads the specifies number of bytes into <paramref name="buffer"/>.
 /// This method reads directly from the underlying stream.
 /// </summary>
 /// <param name="buffer">buffer to read into</param>
 /// <param name="index">starting position in the buffer</param>
 /// <param name="count">number of bytes to write</param>
 /// <returns>number of chars read</returns>
 public int Read(char[] buffer, int index, int count)
 {
     if (reader == null)
     {
         reader = new BinaryReader(stream);
     }
     return(reader.Read(buffer, index, count));
 }
Beispiel #42
0
    public Crawler Fetch()
    {
        System.Net.HttpWebRequest httpWebRequest = System.Net.WebRequest.Create(this.SourceUrl) as System.Net.HttpWebRequest;
        Crawler result;

        using (System.Net.HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as System.Net.HttpWebResponse)
        {
            if (httpWebResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                this.State = string.Concat(new object[]
                {
                    "Url returns ",
                    httpWebResponse.StatusCode,
                    ", ",
                    httpWebResponse.StatusDescription
                });
                result = this;
            }
            else if (httpWebResponse.ContentType.IndexOf("image") == -1)
            {
                this.State = "Url is not an image";
                result     = this;
            }
            else
            {
                this.ServerUrl = PathFormatter.Format(System.IO.Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat"));
                string path = this.Server.MapPath(this.ServerUrl);
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                }
                try
                {
                    System.IO.Stream       responseStream = httpWebResponse.GetResponseStream();
                    System.IO.BinaryReader binaryReader   = new System.IO.BinaryReader(responseStream);
                    byte[] bytes;
                    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                    {
                        byte[] array = new byte[4096];
                        int    count;
                        while ((count = binaryReader.Read(array, 0, array.Length)) != 0)
                        {
                            memoryStream.Write(array, 0, count);
                        }
                        bytes = memoryStream.ToArray();
                    }
                    System.IO.File.WriteAllBytes(path, bytes);
                    this.State = "SUCCESS";
                }
                catch (System.Exception ex)
                {
                    this.State = "抓取错误:" + ex.Message;
                }
                result = this;
            }
        }
        return(result);
    }
Beispiel #43
0
        /// <summary>
        /// 分析网络数据包并进行转换为信息对象
        /// </summary>
        /// <param name="packs">接收到的封包对象</param>
        /// <returns></returns>
        /// <remarks>
        /// 对于分包消息,如果收到的只是片段并且尚未接收完全,则不会进行解析
        /// </remarks>
        public static Msg ParseToMessage(params PacketNetWorkMsg[] packs)
        {
            if (packs.Length == 0 || (packs[0].PackageCount > 1 && packs.Length != packs[0].PackageCount))
            {
                return(null);
            }


            var ms = DecompressMessagePacks(packs);

            if (ms == null)
            {
                //事件
                OnDecompressFailed(new PackageEventArgs(packs));
                return(null);
            }
            //构造读取流
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms, System.Text.Encoding.Unicode);
            //开始读出数据
            Msg m = new Msg(packs[0].RemoteIP);

            m.PackageNo = br.ReadInt64();          //包编号

            m.UserName = br.ReadString();          //用户名
            m.HostName = br.ReadString();          //主机名
            m.Command  = (Commands)br.ReadInt64(); //命令
            m.Type     = (Consts)br.ReadInt64();   //数据类型
            int length = br.ReadInt32();           //数据长度

            m.NormalMsgBytes = new byte[length];
            br.Read(m.NormalMsgBytes, 0, length);     //读取内容

            length = br.ReadInt32();                  //附加数据长度
            m.ExtendMessageBytes = new byte[length];
            br.Read(m.ExtendMessageBytes, 0, length); //读取附加数据

            if (m.Type == Consts.MESSAGE_TEXT)
            {
                m.NormalMsg          = System.Text.Encoding.Unicode.GetString(m.NormalMsgBytes, 0, m.NormalMsgBytes.Length);         //正文
                m.ExtendMessage      = System.Text.Encoding.Unicode.GetString(m.ExtendMessageBytes, 0, m.ExtendMessageBytes.Length); //扩展消息
                m.ExtendMessageBytes = null;
                m.NormalMsgBytes     = null;
            }
            return(m);
        }
        protected static void CopyStream(System.IO.BinaryReader dataReader, System.IO.BinaryWriter dataWriter)
        {
            byte[] buffer = new byte[2048];
            int    len;

            while ((len = dataReader.Read(buffer, 0, 2048)) > 0)
            {
                dataWriter.Write(buffer, 0, len);
            }
        }
Beispiel #45
0
        internal static Face GetResource(string resource)
        {
            System.IO.BinaryReader reader = new System.IO.BinaryReader(Assembly.GetManifestResourceStream(resource));
            byte[] buffer = new byte[reader.BaseStream.Length];
            reader.Read(buffer, 0, buffer.Length);
            reader.Close();

            Face face = FreetypeLibrary.NewMemoryFace(buffer, 0);

            return(face);
        }
Beispiel #46
0
        private void HandleConnect(System.IO.BinaryReader buffer)
        {
            var length = buffer.ReadInt32();

            byte[] bf = new byte[length];
            buffer.Read(bf, 0, length);
            this.Name = Encoding.UTF8.GetString(bf);
            //addTolog(Name);
            this.NotifyNewUser();
            this.SendUserList();
        }
Beispiel #47
0
        /// <summary>
        /// Image: prefix[6] + change[1] + size[1] + message_bytes
        /// </summary>
        public void CaptureTextFromPosition(out int change, out string message, Screen screen)
        {
            change  = 0;
            message = null;
            if (screen == null)
            {
                return;
            }
            var x  = SettingsManager.Options.DisplayMonitorPositionX;
            var y  = SettingsManager.Options.DisplayMonitorPositionY;
            var sw = screen.Bounds.Width;
            var sh = screen.Bounds.Height;
            // Make sure take pixel pairs till the end of the line.
            var length = sw - x;

            length = length - (length % 2);
            // Take screenshot of the line.
            Basic.CaptureImage(ref lineBitmap, screen.Bounds.X + x, screen.Bounds.Y + y, length, 1);
            // var asm = new JocysCom.ClassLibrary.Configuration.AssemblyInfo();
            // var path = asm.GetAppDataPath(false, "Images\\Screen_{0:yyyyMMdd_HHmmss_fff}.png", DateTime.Now);
            // lineBitmap.Save(path, ImageFormat.Png);
            Basic.GetImageBytes(ref lineBytes, lineBitmap);
            var prefixBytes = SettingsManager.Options.DisplayMonitorHavePixelSpaces
                                ? ColorPrefixBytesBlanked
                                : ColorPrefixBytes;
            var index = JocysCom.ClassLibrary.Text.Helper.IndexOf(lineBytes, prefixBytes);

            // If not found then...
            if (index == -1)
            {
                return;
            }
            //	StatusTextBox.Text += string.Format("Prefix found");
            if (SettingsManager.Options.DisplayMonitorHavePixelSpaces)
            {
                RemoveBlankPixels(lineBytes, ref lineBufferNoBlanks);
            }
            else
            {
                lineBufferNoBlanks = lineBytes;
            }
            var prefix = ColorPrefixBytes;
            // Skip prefix.
            var ms = new MemoryStream(lineBufferNoBlanks, prefix.Length, lineBufferNoBlanks.Length - prefix.Length);
            var br = new System.IO.BinaryReader(ms);

            change = ReadRgbInt(br);
            var messageSize  = ReadRgbInt(br);
            var messageBytes = new byte[messageSize];

            br.Read(messageBytes, 0, messageSize);
            message = System.Text.Encoding.UTF8.GetString(messageBytes);
            br.Dispose();
        }
    // 動画のバイナリをリソースからロードする処理
    private static byte[] LoadVideoBinary()
    {
        System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
        Stream       stream = assembly.GetManifestResourceStream("OpenBrowser.mp4");
        BinaryReader reader = new System.IO.BinaryReader(stream);
        int          len    = (int)stream.Length;

        byte[] buf = new Byte[len];
        reader.Read(buf, 0, len);
        reader.Dispose();
        return(buf);
    }
Beispiel #49
0
    public void Deserialize(System.IO.Stream stream)
    {
        //stream.Seek(0, System.IO.SeekOrigin.Begin);
        System.IO.BinaryReader reader = new System.IO.BinaryReader(stream, System.Text.Encoding.Default, true);


        location_x = reader.ReadInt32();
        location_y = reader.ReadInt32();
        location_z = reader.ReadInt32();

        heightmap = new float[20 * 20];
        byte[] h_buff = new byte[heightmap.Length * 4];
        reader.Read(h_buff, 0, h_buff.Length);
        Buffer.BlockCopy(h_buff, 0, heightmap, 0, h_buff.Length);

        // Chunk 0
        c0_min = reader.ReadByte();
        c0_max = reader.ReadByte();

        blocks_type_c0 = new byte[20 * 20 * 128];
        reader.Read(blocks_type_c0, 0, blocks_type_c0.Length);

        blocks_iso_c0 = new float[20 * 20 * 128];
        byte[] iso_buf = new byte[blocks_iso_c0.Length * 4];
        reader.Read(iso_buf, 0, iso_buf.Length);
        Buffer.BlockCopy(iso_buf, 0, blocks_iso_c0, 0, iso_buf.Length);

        // Chunk 1
        c1_min = reader.ReadByte();
        c1_max = reader.ReadByte();

        blocks_type_c1 = new byte[20 * 20 * 128];
        reader.Read(blocks_type_c1, 0, blocks_type_c1.Length);

        blocks_iso_c1 = new float[20 * 20 * 128];
        reader.Read(iso_buf, 0, iso_buf.Length);
        Buffer.BlockCopy(iso_buf, 0, blocks_iso_c1, 0, iso_buf.Length);

        reader.Close();
    }
        public static float[] load_binary_file(string filepath, int N)
        {
            Console.WriteLine("Loading " + filepath);
            var buffer = new byte[sizeof(float) * N];

            using (var reader = new System.IO.BinaryReader(System.IO.File.OpenRead(filepath))) {
                reader.Read(buffer, 0, buffer.Length);
            }
            var dst = new float[N];

            System.Buffer.BlockCopy(buffer, 0, dst, 0, buffer.Length);
            return(dst);
        }
        private void WriteContent(XmlWriter writer)
        {
            using (System.IO.BinaryReader br = new System.IO.BinaryReader(stream))
            {
                byte[] buffer    = new byte[BufferSize];
                int    readBytes = 0;

                while ((readBytes = br.Read(buffer, 0, BufferSize)) != 0)
                {
                    writer.WriteBase64(buffer, 0, readBytes);
                }
            }
        }
Beispiel #52
0
 static public int Read(IntPtr l)
 {
     try {
         System.IO.BinaryReader self = (System.IO.BinaryReader)checkSelf(l);
         var ret = self.Read();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    public static string ReturnMD5Code(string FilePath)
    {
#if !PCL
        try
        {
#if WINDOWS_PHONE_APP
            var _file = Windows.Storage.StorageFile.GetFileFromPathAsync(FilePath).GetResults();
            if (_file != null)
#else
            var _file = new System.IO.FileInfo(FilePath);
            if (_file.Exists)
#endif
            {
                var _md5 = Md5.Create();

#if WINDOWS_PHONE_APP
                using (var _reader = new System.IO.BinaryReader(_file.OpenStreamForReadAsync().Result))
#else
                using (var _reader = new System.IO.BinaryReader(_file.Open(FileMode.Open)))
#endif
                {
                    var _buffer = new byte[_reader.BaseStream.Length];
                    _reader.Read(_buffer, 0, _buffer.Length);
#if !WINDOWS_PHONE_APP
                    _reader.Close();
#endif
                    var _hash = _md5.ComputeHash(_buffer);

                    var _ret = new System.Text.StringBuilder();
                    for (int i = 0; i < _hash.Length; i++)
                    {
                        _ret.Append(_hash[i].ToString("X2"));
                    }

                    return(_ret.ToString());
                }
            }
            else
            {
                return("");
            }
        }
        catch (Exception ex)
        {
            return("");
        }
#else
        return("");
#endif
    }
Beispiel #54
0
        //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
        public static sbyte[] readBytes(System.IO.BinaryReader in_Renamed)
        {
            int size = (int)ExtUtil.readNumeric(in_Renamed);

            sbyte[] bytes  = new sbyte[size];
            int     read   = 0;
            int     toread = size;

            while (read != size)
            {
                read    = in_Renamed.Read((byte[])(Array)bytes, 0, toread);
                toread -= read;
            }
            return(bytes);
        }
Beispiel #55
0
            private static uint?ReadUInt32(double?d, bool specified, System.IO.BinaryReader binaryReader)
            {
                if (specified)
                {
                    if (d.HasValue)
                    {
                        return((uint)d.Value);
                    }

                    var buffer     = new byte[4];
                    var actualSize = binaryReader.Read(buffer, 0, buffer.Length);
                    return(actualSize != buffer.Length ? null : (uint?)BitConverter.ToUInt32(buffer, 0));
                }
                return(null);
            }
Beispiel #56
0
            private static byte?ReadByte(byte?byteValue, bool specified, System.IO.BinaryReader binaryReader)
            {
                if (specified)
                {
                    if (byteValue.HasValue)
                    {
                        return(byteValue);
                    }

                    var buffer     = new byte[1];
                    var actualSize = binaryReader.Read(buffer, 0, buffer.Length);
                    return(actualSize != buffer.Length ? null : (byte?)buffer[0]);
                }
                return(null);
            }
Beispiel #57
0
            private static ushort?ReadUShort(double?value, bool specified, System.IO.BinaryReader binaryReader)
            {
                if (specified)
                {
                    if (value.HasValue)
                    {
                        return((ushort)value.Value);
                    }

                    var buffer     = new byte[2];
                    var actualSize = binaryReader.Read(buffer, 0, buffer.Length);
                    return(actualSize != buffer.Length ? null : (ushort?)BitConverter.ToUInt16(buffer, 0));
                }
                return(null);
            }
Beispiel #58
0
        public void LoadStateBinary(System.IO.BinaryReader reader)
        {
            int newlen = reader.ReadInt32();

            if (newlen > savebuff.Length)
            {
                throw new Exception("Unexpected buffer size");
            }
            reader.Read(savebuff, 0, newlen);
            api.CMD_Unserialize(savebuff);
            // other variables
            Frame      = reader.ReadInt32();
            LagCount   = reader.ReadInt32();
            IsLagFrame = reader.ReadBoolean();
        }
Beispiel #59
0
        /// <summary>
        /// Image: prefix[6] + change[1] + size[1] + message_bytes
        /// </summary>
        public void CaptureTextFromPosition(out int change, out string message)
        {
            change  = 0;
            message = null;
            var x      = SettingsManager.Options.DisplayMonitorPositionX;
            var y      = SettingsManager.Options.DisplayMonitorPositionY;
            var screen = System.Windows.Forms.Screen.PrimaryScreen;
            var sw     = screen.Bounds.Width;
            var sh     = screen.Bounds.Height;
            // Make sure take pixel pairs till the end of the line.
            var length = sw - x;

            length = length - (length % 2);
            // Take screenshot of the line.
            Basic.CaptureImage(ref lineBitmap, x, y, length, 1);
            Basic.GetImageBytes(ref lineBytes, lineBitmap);
            var prefixBytes = SettingsManager.Options.DisplayMonitorHavePixelSpaces
                                ? ColorPrefixBytesBlanked
                                : ColorPrefixBytes;
            var index = JocysCom.ClassLibrary.Text.Helper.IndexOf(lineBytes, prefixBytes);

            // If not found then...
            if (index == -1)
            {
                return;
            }
            //	StatusTextBox.Text += string.Format("Prefix found");
            if (SettingsManager.Options.DisplayMonitorHavePixelSpaces)
            {
                RemoveBlankPixels(lineBytes, ref lineBufferNoBlanks);
            }
            else
            {
                lineBufferNoBlanks = lineBytes;
            }
            var prefix = ColorPrefixBytes;
            // Skip prefix.
            var ms = new MemoryStream(lineBufferNoBlanks, prefix.Length, lineBufferNoBlanks.Length - prefix.Length);
            var br = new System.IO.BinaryReader(ms);

            change = ReadRgbInt(br);
            var messageSize  = ReadRgbInt(br);
            var messageBytes = new byte[messageSize];

            br.Read(messageBytes, 0, messageSize);
            message = System.Text.Encoding.UTF8.GetString(messageBytes);
            br.Dispose();
        }
Beispiel #60
0
        public void LoadStateBinary(System.IO.BinaryReader reader)
        {
            CheckDisposed();
            int len = reader.ReadInt32();

            if (len != SaveStateBuff.Length)
            {
                throw new InvalidOperationException("Unexpected savestate buffer length!");
            }
            reader.Read(SaveStateBuff, 0, SaveStateBuff.Length);
            LibQuickNES.ThrowStringError(QN.qn_state_load(Context, SaveStateBuff, SaveStateBuff.Length));
            // other variables
            IsLagFrame = reader.ReadBoolean();
            LagCount   = reader.ReadInt32();
            Frame      = reader.ReadInt32();
        }