static ushort[] Expand(string resourceName) { using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) { ushort[] result = new ushort[reader.ReadUInt16()]; ushort escape = reader.ReadUInt16(); int w = 0; while (stream.Position < stream.Length) { ushort value = reader.ReadUInt16(); if (value == escape) { ushort count = reader.ReadUInt16(); value = reader.ReadUInt16(); while (count > 0) { result[w++] = value; count--; } } else { result[w++] = value; } } return(result); } }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.HighLatency2Message message = new MavLink4Net.Messages.Common.HighLatency2Message(); message.Timestamp = reader.ReadUInt32(); message.Latitude = reader.ReadInt32(); message.Longitude = reader.ReadInt32(); message.CustomMode = reader.ReadUInt16(); message.Altitude = reader.ReadInt16(); message.TargetAltitude = reader.ReadInt16(); message.TargetDistance = reader.ReadUInt16(); message.WpNum = reader.ReadUInt16(); message.FailureFlags = ((MavLink4Net.Messages.Common.HlFailureFlag)(reader.ReadUInt16())); message.Type = ((MavLink4Net.Messages.Common.Type)(reader.ReadByte())); message.Autopilot = ((MavLink4Net.Messages.Common.Autopilot)(reader.ReadByte())); message.Heading = reader.ReadByte(); message.TargetHeading = reader.ReadByte(); message.Throttle = reader.ReadByte(); message.Airspeed = reader.ReadByte(); message.AirspeedSp = reader.ReadByte(); message.Groundspeed = reader.ReadByte(); message.Windspeed = reader.ReadByte(); message.WindHeading = reader.ReadByte(); message.Eph = reader.ReadByte(); message.Epv = reader.ReadByte(); message.TemperatureAir = reader.ReadSByte(); message.ClimbRate = reader.ReadSByte(); message.Battery = reader.ReadSByte(); message.Custom0 = reader.ReadSByte(); message.Custom1 = reader.ReadSByte(); message.Custom2 = reader.ReadSByte(); return(message); }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.AdsbVehicleMessage message = new MavLink4Net.Messages.Common.AdsbVehicleMessage(); message.IcaoAddress = reader.ReadUInt32(); message.Lat = reader.ReadInt32(); message.Lon = reader.ReadInt32(); message.Altitude = reader.ReadInt32(); message.Heading = reader.ReadUInt16(); message.HorVelocity = reader.ReadUInt16(); message.VerVelocity = reader.ReadInt16(); message.Flags = ((MavLink4Net.Messages.Common.AdsbFlags)(reader.ReadUInt16())); message.Squawk = reader.ReadUInt16(); message.AltitudeType = ((MavLink4Net.Messages.Common.AdsbAltitudeType)(reader.ReadByte())); message.Callsign[0] = reader.ReadChar(); message.Callsign[1] = reader.ReadChar(); message.Callsign[2] = reader.ReadChar(); message.Callsign[3] = reader.ReadChar(); message.Callsign[4] = reader.ReadChar(); message.Callsign[5] = reader.ReadChar(); message.Callsign[6] = reader.ReadChar(); message.Callsign[7] = reader.ReadChar(); message.Callsign[8] = reader.ReadChar(); message.EmitterType = ((MavLink4Net.Messages.Common.AdsbEmitterType)(reader.ReadByte())); message.Tslc = reader.ReadByte(); return(message); }
public static CardInfo FromBytes(byte[] rawData) { if (rawData.Length != 16) { throw new NotSupportedException(); } var result = null as CardInfo; try { using (var stream = new System.IO.MemoryStream(rawData)) { using (var reader = new System.IO.BinaryReader(stream)) { result = new CardInfo(); result.Raw = rawData; reader.ReadBytes(8); var b8 = reader.ReadByte(); result.CardType = (byte)((b8 & 0xF0) >> 4); result.LastPaymentRegionCode = (byte)(b8 & 0x0F); reader.ReadBytes(2); result.Balance = reader.ReadUInt16(); reader.ReadByte(); result.UpdateNumber = reader.ReadUInt16(); } } } catch { } return(result); }
/// <summary> /// Unserializes a BinaryStream into the Attributes of this Instance /// </summary> /// <param name="reader">The Stream that contains the FileData</param> protected override void Unserialize(System.IO.BinaryReader reader) { lines = new Hashtable(); if (reader.BaseStream.Length <= 0x40) { return; } byte[] fi = reader.ReadBytes(0x40); SimPe.Data.MetaData.FormatCode fo = (SimPe.Data.MetaData.FormatCode)reader.ReadUInt16(); if (fo != Data.MetaData.FormatCode.normal) { return; } ushort count = reader.ReadUInt16(); filename = fi; format = fo; lines = new Hashtable(); if ((limit != 0) && (count > limit)) { count = (ushort)limit; // limit number of StrItem entries loaded } for (int i = 0; i < count; i++) { StrToken.Unserialize(reader, lines); } }
/// <summary> /// Process a PCAP Next Generation name resolution block /// </summary> /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param> /// <param name="thePacketPayloadLength">The payload length of the packet read from the packet capture</param> /// <returns>Boolean flag that indicates whether the PCAP Next Generation name resolution block could be processed</returns> private static bool ProcessNameResolutionBlock(System.IO.BinaryReader theBinaryReader, out long thePacketPayloadLength) { bool theResult = true; // We have got a PCAP Next Generation name resolution block // The PCAP Next Generation name resolution block does not contain an Ethernet frame // Set up the output parameter for the length of the PCAP Next Generation packet capture packet payload // Set this output parameter to a value of zero to prevent any attempt to process an Ethernet frame from the PCAP Next Generation packet capture packet payload thePacketPayloadLength = 0; // Just read off the block type for the PCAP Next Generation name resolution block so we can move on theBinaryReader.ReadUInt32(); // Read off and store the block total length for the PCAP Next Generation name resolution block, adjusting it up to the next even four byte boundary, for use below uint theBlockTotalLength = AdjustBlockTotalLength( theBinaryReader.ReadUInt32()); // Just read off the record type for the PCAP Next Generation name resolution block so we can move on theBinaryReader.ReadUInt16(); // Just read off the record length for the PCAP Next Generation name resolution block so we can move on theBinaryReader.ReadUInt16(); // The PCAP Next Generation name resolution block does not contain an Ethernet frame // Just read the bytes off the remaining bytes from the PCAP Next Generation name resolution block so we can continue theBinaryReader.ReadBytes( (int)(theBlockTotalLength - (uint)Constants.BlockTotalLength.NameResolutionBlock)); return(theResult); }
/// <summary> /// 从文件中创建码表 /// </summary> /// <param name="name">文件名</param> public CodeTable(string name) { Init(InitType.Empty); System.IO.FileStream fs = System.IO.File.OpenRead(name); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); int n = br.ReadInt32(); for (int i = 1; i <= n; i++) { int jis = br.ReadUInt16(); int ucs = br.ReadUInt16(); int j = jis2i[jis]; { i2ucs[j] = ucs; ucs2i[ucs] = j; } if (j > _index) { _index = j; } } br.Close(); fs.Close(); }
/// <summary>Checks whether a specified file is a valid Win32 plugin.</summary> /// <param name="file">The file to check.</param> /// <returns>Whether the file is a valid Win32 plugin.</returns> internal static bool CheckWin32Header(string file) { using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) { if (reader.ReadUInt16() != 0x5A4D) { /* Not MZ signature */ return(false); } stream.Position = 0x3C; stream.Position = reader.ReadInt32(); if (reader.ReadUInt32() != 0x00004550) { /* Not PE signature */ return(false); } if (reader.ReadUInt16() != 0x014C) { /* Not IMAGE_FILE_MACHINE_I386 */ return(false); } } } return(true); }
protected override void Unserialize(System.IO.BinaryReader reader) { uint id = reader.ReadUInt32(); if (id != 0x00000001) { throw new Exception("File is not Recognized by the Family Ties Wrapper!"); } int count = reader.ReadInt32(); sims = new ArrayList(count); for (int i = 0; i < count; i++) { ushort instance = reader.ReadUInt16(); int blockdel = reader.ReadInt32(); FamilyTieItem[] items = new FamilyTieItem[reader.ReadInt32()]; for (int k = 0; k < items.Length; k++) { MetaData.FamilyTieTypes type = (MetaData.FamilyTieTypes)reader.ReadUInt32(); ushort tinstance = reader.ReadUInt16(); items[k] = new FamilyTieItem(type, tinstance, this); } FamilyTieSim simtie = new FamilyTieSim(instance, items, this); simtie.BlockDelimiter = blockdel; sims.Add(simtie); } }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.HighLatencyMessage message = new MavLink4Net.Messages.Common.HighLatencyMessage(); message.CustomMode = reader.ReadUInt32(); message.Latitude = reader.ReadInt32(); message.Longitude = reader.ReadInt32(); message.Roll = reader.ReadInt16(); message.Pitch = reader.ReadInt16(); message.Heading = reader.ReadUInt16(); message.HeadingSp = reader.ReadInt16(); message.AltitudeAmsl = reader.ReadInt16(); message.AltitudeSp = reader.ReadInt16(); message.WpDistance = reader.ReadUInt16(); message.BaseMode = ((MavLink4Net.Messages.Common.ModeFlag)(reader.ReadByte())); message.LandedState = ((MavLink4Net.Messages.Common.LandedState)(reader.ReadByte())); message.Throttle = reader.ReadSByte(); message.Airspeed = reader.ReadByte(); message.AirspeedSp = reader.ReadByte(); message.Groundspeed = reader.ReadByte(); message.ClimbRate = reader.ReadSByte(); message.GpsNsat = reader.ReadByte(); message.GpsFixType = ((MavLink4Net.Messages.Common.GpsFixType)(reader.ReadByte())); message.BatteryRemaining = reader.ReadByte(); message.Temperature = reader.ReadSByte(); message.TemperatureAir = reader.ReadSByte(); message.Failsafe = reader.ReadByte(); message.WpNum = reader.ReadByte(); return(message); }
public void Read(System.IO.BinaryReader inFile, ushort version) { StageIndex = inFile.ReadUInt16(); Position = inFile.ReadString(); Position_Group = inFile.ReadString(); Weight = inFile.ReadUInt16(); Experience = inFile.ReadByte(); Team = inFile.ReadByte(); Loyalty = inFile.ReadByte(); Play_for_Winner = inFile.ReadByte(); Personality_Strength = inFile.ReadByte(); Leadership = inFile.ReadByte(); Intelligence = inFile.ReadByte(); Mentor = inFile.ReadByte(); Volatility = inFile.ReadByte(); Popularity = inFile.ReadByte(); CurBars = inFile.ReadBytes((int)DataReader.FOFData.ScoutBars.Count); FutBars = inFile.ReadBytes((int)DataReader.FOFData.ScoutBars.Count); CurOverall = inFile.ReadByte(); FutOverall = inFile.ReadByte(); if (version >= 3) { Dash = inFile.ReadUInt16(); Solecismic = inFile.ReadByte(); Strength = inFile.ReadByte(); Agility = inFile.ReadUInt16(); Jump = inFile.ReadByte(); Position_Specific = inFile.ReadByte(); } }
public static bool LoadEntity(Client.GameClient client) { using (var cmd = new MySqlCommand(MySqlCommandType.SELECT).Select("characters").Where("UID", client.Account.EntityID)) using (var reader = new MySqlReader(cmd)) { if (reader.Read()) { try { client.Entity = new Entity(); client.Entity.Owner = client; client.Entity.UID = reader.ReadUInt32("UID"); client.Entity.Experience = reader.ReadUInt32("Experience"); client.Entity.Clan = reader.ReadString("Clan"); client.Entity.Name = reader.ReadString("Name"); client.Entity.Deserion = reader.ReadUInt32("Deserion"); client.Entity.GeneradeKills = reader.ReadUInt32("GeneradeKills"); client.Entity.GP = reader.ReadUInt32("GP"); client.Entity.ZP = reader.ReadUInt32("ZP"); client.Entity.MP = reader.ReadUInt32("MP"); client.Entity.VIP = reader.ReadBoolean("VIP"); client.Entity.HeadshotKills = reader.ReadUInt32("HeadshotKills"); client.Entity.KnifeKills = reader.ReadUInt32("KnifeKills"); client.Entity.TeamKills = reader.ReadUInt32("TeamKills"); client.Entity.Settings = reader.ReadBlob("Settings"); client.Entity.Battles = new System.Collections.Generic.List <Battle>(); byte[] Battles = reader.ReadBlob("Battles"); if (Battles.Length > 0) { using (var stream = new System.IO.MemoryStream(Battles)) using (var rdr = new System.IO.BinaryReader(stream)) { int count = rdr.ReadInt32(); for (int i = 0; i < count; i++) { Battle battle = new Battle { GameMode = (Enums.GameMode)rdr.ReadByte(), Won = rdr.ReadBoolean(), Kills = rdr.ReadUInt16(), Deaths = rdr.ReadUInt16() }; client.Entity.Battles.Add(battle); } } } return(true); } catch (Exception e) { Console.WriteLine(e); return(false); } } else { return(false); } } }
public ExportedLevel(System.IO.BinaryReader br) { string Header = br.ReadString(); if (Header != fileHeader) { throw new Exception(LanguageManager.Get("NSMBLevel", "InvalidFile")); } ushort FileVersion = br.ReadUInt16(); if (FileVersion > version) { throw new Exception(LanguageManager.Get("NSMBLevel", "OldVersion")); } LevelFileID = br.ReadUInt16(); BGDatFileID = br.ReadUInt16(); int LevelFileLength = br.ReadInt32(); LevelFile = br.ReadBytes(LevelFileLength); int BGFileLength = br.ReadInt32(); BGDatFile = br.ReadBytes(BGFileLength); }
private void Unserialize(System.IO.BinaryReader reader) { setVersion(reader.ReadUInt32()); simId = reader.ReadUInt16(); wantId = reader.ReadUInt32(); setArgType((ArgTypes)reader.ReadByte()); switch (argType) { case ArgTypes.Sim: if (version >= 0x08) { setArgUshort(argType, 0x08, reader.ReadUInt16()); } break; case ArgTypes.Guid: setArgUint(argType, reader.ReadUInt32()); break; case ArgTypes.Category: setArgUint(argType, reader.ReadUInt32()); break; case ArgTypes.Skill: setArgUshort(argType, 0, reader.ReadUInt16()); break; case ArgTypes.Career: setArgUint(argType, reader.ReadUInt32()); break; case ArgTypes.Badge: setArgUint(argType, reader.ReadUInt32()); break; default: arg = null; break; } arg2 = reader.ReadUInt16(); counter = reader.ReadUInt32(); score = reader.ReadInt32(); influence = version >= 0x09 ? reader.ReadInt32() : 0; flags = reader.ReadByte(); }
/// <summary> /// Reads the Data from a Stream /// </summary> /// <param name="format"></param> /// <param name="reader"></param> private void Unserialize(System.IO.BinaryReader reader) { opcode = reader.ReadUInt16(); if (((Bhav)parent).Header.Format < 0x8007) { addr1 = formatSpecificSetAddr((ushort)reader.ReadByte()); addr2 = formatSpecificSetAddr((ushort)reader.ReadByte()); } else { addr1 = formatSpecificSetAddr(reader.ReadUInt16()); addr2 = formatSpecificSetAddr(reader.ReadUInt16()); } if (((Bhav)parent).Header.Format < 0x8003) { nodeversion = 0; operands = new wrappedByteArray(this, reader); reserved_01 = new wrappedByteArray(this, new byte[8]); } else if (((Bhav)parent).Header.Format < 0x8005) { nodeversion = 0; operands = new wrappedByteArray(this, reader); reserved_01 = new wrappedByteArray(this, reader); } else { nodeversion = reader.ReadByte(); operands = new wrappedByteArray(this, reader); reserved_01 = new wrappedByteArray(this, reader); } }
protected override void DataUpdate() { System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream); ByteStream.Position = 0; SomeUInt32 = BSReader.ReadUInt32(); SomeNumber = BSReader.ReadUInt32(); SomeFlag = BSReader.ReadUInt32(); for (int i = 0; i <= 2; i++) { Coordinate[i].X = BSReader.ReadSingle(); Coordinate[i].Y = BSReader.ReadSingle(); Coordinate[i].Z = BSReader.ReadSingle(); Coordinate[i].W = BSReader.ReadSingle(); } SectionSize = BSReader.ReadInt32(); SectionSize = BSReader.ReadInt32(); SectionHead = BSReader.ReadUInt32(); Array.Resize(ref SomeUInt16, SectionSize); for (int i = 0; i <= SectionSize - 1; i++) { SomeUInt16[i] = BSReader.ReadUInt16(); } SomeUInt161 = BSReader.ReadUInt16(); SomeUInt162 = BSReader.ReadUInt16(); SomeUInt163 = BSReader.ReadUInt16(); SomeUInt164 = BSReader.ReadUInt16(); }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.ParamValueMessage message = new MavLink4Net.Messages.Common.ParamValueMessage(); message.ParamValue = reader.ReadSingle(); message.ParamCount = reader.ReadUInt16(); message.ParamIndex = reader.ReadUInt16(); message.ParamId[0] = reader.ReadChar(); message.ParamId[1] = reader.ReadChar(); message.ParamId[2] = reader.ReadChar(); message.ParamId[3] = reader.ReadChar(); message.ParamId[4] = reader.ReadChar(); message.ParamId[5] = reader.ReadChar(); message.ParamId[6] = reader.ReadChar(); message.ParamId[7] = reader.ReadChar(); message.ParamId[8] = reader.ReadChar(); message.ParamId[9] = reader.ReadChar(); message.ParamId[10] = reader.ReadChar(); message.ParamId[11] = reader.ReadChar(); message.ParamId[12] = reader.ReadChar(); message.ParamId[13] = reader.ReadChar(); message.ParamId[14] = reader.ReadChar(); message.ParamId[15] = reader.ReadChar(); message.ParamType = ((MavLink4Net.Messages.Common.ParamType)(reader.ReadByte())); return(message); }
/// <summary> /// 判断dll文件是64位还是32位[true:64位;false:32位;.NET AnyCpu程序集判断为32位] /// </summary> /// <param name="dllFilePath">dll文件路径</param> /// <returns>[true:64位;false:32位;.NET AnyCpu程序集判断为32位]</returns> public static bool IsX64OrX86(string dllFilePath) { using (System.IO.FileStream fStream = new System.IO.FileStream(dllFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream); if (bReader.ReadUInt16() != 23117) //check the MZ signature { throw new Exception("不识别的dll"); } fStream.Seek(0x3A, System.IO.SeekOrigin.Current); //seek to e_lfanew. fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); //seek to the start of the NT header. if (bReader.ReadUInt32() != 17744) //check the PE\0\0 signature. { throw new Exception("不识别的dll"); } fStream.Seek(20, System.IO.SeekOrigin.Current); //seek past the file header, ushort architecture = bReader.ReadUInt16(); //read the magic number of the optional header. //523 64位 267 32位 switch (architecture) { case 523: return(true); case 267: return(false); default: throw new Exception("不识别的dll类型"); } } }
protected static ushort GetPEArchitecture(string pFilePath) { ushort architecture = 0; try { using (System.IO.FileStream fStream = new System.IO.FileStream(pFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream)) { if (bReader.ReadUInt16() == 23117) //check the MZ signature { fStream.Seek(0x3A, System.IO.SeekOrigin.Current); //seek to e_lfanew. fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); //seek to the start of the NT header. if (bReader.ReadUInt32() == 17744) //check the PE\0\0 signature. { fStream.Seek(20, System.IO.SeekOrigin.Current); //seek past the file header, architecture = bReader.ReadUInt16(); //read the magic number of the optional header. } } } } } catch (Exception) { } // if architecture returns 0, there has been an error. return(architecture); }
private void LoadProgram() { var fileStream = new System.IO.FileStream(programFileName, System.IO.FileMode.Open); var binaryReader = new System.IO.BinaryReader(fileStream); var magicWordBytes = binaryReader.ReadBytes(8); var magicWord = System.Text.Encoding.Default.GetString(magicWordBytes); if (magicWord != "ZHANGSHU") { System.Windows.Forms.MessageBox.Show("It is NOT a VM binary file!", "Error!", MessageBoxButtons.OK); return; } var offset = binaryReader.ReadUInt16(); var length = binaryReader.ReadUInt16(); var position = binaryReader.ReadUInt16(); //where the program starts in memory ushort i = 0; while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length) { memory[(UInt16)(position + i)] = binaryReader.ReadByte(); ++i; } binaryReader.Close(); fileStream.Close(); programPosition = (UInt16)(position + offset - 14); }
public void read(System.IO.BinaryReader reader) { tag = reader.ReadUInt16(); int typeID = reader.ReadUInt16(); int count = reader.ReadInt32(); TiffData.TIFFdataType tifType; if (Enum.IsDefined(typeof(TiffData.TIFFdataType), typeID)) { tifType = (TiffData.TIFFdataType)typeID; } else { tifType = TiffData.TIFFdataType.Undefined; } data = new TiffData(tifType, count); if (data.dataLength() <= 4) { readData(reader); offset = -1; } else { offset = reader.ReadUInt32(); } }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.PowerStatusMessage message = new MavLink4Net.Messages.Common.PowerStatusMessage(); message.Vcc = reader.ReadUInt16(); message.Vservo = reader.ReadUInt16(); message.Flags = ((MavLink4Net.Messages.Common.PowerStatus)(reader.ReadUInt16())); return(message); }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.LogRequestListMessage message = new MavLink4Net.Messages.Common.LogRequestListMessage(); message.Start = reader.ReadUInt16(); message.End = reader.ReadUInt16(); message.TargetSystem = reader.ReadByte(); message.TargetComponent = reader.ReadByte(); return(message); }
public void Read(System.IO.BinaryReader br) { XOrigin = br.ReadUInt16(); YOrigin = br.ReadUInt16(); Width = br.ReadUInt16(); Height = br.ReadUInt16(); PixelDepth = br.ReadByte(); Descriptor = br.ReadByte(); }
public AccountTable(string username) { if (username == null) { return; } this.Username = username; this.Password = ""; this.IP = ""; this.State = Enums.AccountState.Default; this.EntityID = 0; using (var cmd = new MySqlCommand(MySqlCommandType.SELECT).Select("accounts").Where("Username", username)) using (var reader = new MySqlReader(cmd)) { if (reader.Read()) { exists = true; this.Password = reader.ReadString("Password"); this.IP = reader.ReadString("Ip"); this.EntityID = reader.ReadUInt32("EntityID"); this.State = (Enums.AccountState)reader.ReadInt32("State"); using (var cmd2 = new MySqlCommand(MySqlCommandType.SELECT).Select("characters").Where("UID", EntityID)) using (var reader2 = new MySqlReader(cmd2)) { if (reader2.Read()) { Name = reader2.ReadString("Name"); Rank = (ushort)Entity.RankExperiences.Where(i => i.Value >= reader2.ReadUInt32("Experience")).FirstOrDefault().Key; byte[] Battles = reader2.ReadBlob("Battles"); var battles = new List <Battle>(); if (Battles.Length > 0) { using (var stream = new System.IO.MemoryStream(Battles)) using (var rdr = new System.IO.BinaryReader(stream)) { int count = rdr.ReadInt32(); for (int i = 0; i < count; i++) { Battle battle = new Battle { GameMode = (Enums.GameMode)rdr.ReadByte(), Won = rdr.ReadBoolean(), Kills = rdr.ReadUInt16(), Deaths = rdr.ReadUInt16() }; battles.Add(battle); } } } TotalDeaths = (uint)battles.Sum(i => i.Deaths); TotalKills = (uint)battles.Sum(i => i.Kills); } } } } }
//----------ファイル入出力用メソッド------------ //ファイル読み込み public bool Read_File(string filename) { System.IO.FileStream read_file; System.IO.BinaryReader br; if (System.IO.File.Exists(filename)) { using (read_file = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (br = new System.IO.BinaryReader(read_file)) { riff_chunk_ID = br.ReadChars(4); riff_chunk_size = br.ReadUInt32(); riff_form_type = br.ReadChars(4); string ID = new string(riff_chunk_ID); string TYPE = new string(riff_form_type); if (ID == "RIFF" && TYPE == "WAVE") { fmt_chunk_ID = br.ReadChars(4); fmt_chunk_size = br.ReadUInt32(); fmt_wave_format_type = br.ReadUInt16(); fmt_channel = br.ReadUInt16(); fmt_sample_per_sec = br.ReadUInt32(); fmt_bytes_per_sec = br.ReadUInt32(); fmt_block_size = br.ReadUInt16(); fmt_bits_per_sample = br.ReadUInt16(); data_chunk_ID = br.ReadChars(4); data_chunk_size = br.ReadUInt32(); Data_length = data_chunk_size / fmt_block_size; decimal tmp = fmt_sample_per_sec; SampleT = 1 / tmp; if (Read_Data(br)) { Read_success = true; //File_Information(); return(true); } else { Read_success = false; MessageBox.Show("このファイルは読み込めません"); return(false); } } else { Read_success = false; MessageBox.Show("このファイルはWAVEフォーマットではありません。"); return(false); } } } } MessageBox.Show("ファイルが存在しません。"); return(false); }
protected override void DataUpdate() { System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream); ByteStream.Position = 0; I16[0] = BSReader.ReadUInt16(); I16[1] = BSReader.ReadUInt16(); I16[2] = BSReader.ReadUInt16(); I16[3] = BSReader.ReadUInt16(); I16[4] = BSReader.ReadUInt16(); }
public MavLink4Net.Messages.IMessage Deserialize(System.IO.BinaryReader reader) { MavLink4Net.Messages.Common.LogEntryMessage message = new MavLink4Net.Messages.Common.LogEntryMessage(); message.TimeUtc = reader.ReadUInt32(); message.Size = reader.ReadUInt32(); message.Id = reader.ReadUInt16(); message.NumLogs = reader.ReadUInt16(); message.LastLogNum = reader.ReadUInt16(); return(message); }
public void Read(System.IO.BinaryReader r) { this.compressionCode = r.ReadUInt16(); this.numChannels = r.ReadUInt16(); this.sampleRate = r.ReadUInt32(); this.avgBytesPerSecond = r.ReadUInt32(); this.blockAlign = r.ReadUInt16(); this.sigBitsPerSample = r.ReadUInt16(); this.extraFormatBytes = r.ReadUInt16(); }
public static Face ReadFace(this System.IO.BinaryReader reader) { Face face = new Face() { A = reader.ReadUInt16(), B = reader.ReadUInt16(), C = reader.ReadUInt16() }; return(face); }
static void ExtractSPR(string filename) { using (System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead("TIBIA.SPR"))) { ushort count = reader.ReadUInt16(); reader.BaseStream.Seek(6, System.IO.SeekOrigin.Current); for (int a = 1; a < count; a++) { Bitmap bmp = new Bitmap(32, 32, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); bmp.Palette = colorPalette; System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, 32, 32), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); byte[] byteArray = new byte[1024]; for (int b = 0; b < 1024; b++) { byteArray[b] = 0xFF; } long size = reader.ReadUInt16(); size += reader.BaseStream.Position - 1; int i = 0; while (reader.BaseStream.Position <= size) { if (reader.BaseStream.Position >= reader.BaseStream.Length) { break; } ushort tPixels = reader.ReadUInt16(); i += tPixels; if (reader.BaseStream.Position > size) { break; } byte cPixels = reader.ReadByte(); for (int c = 0; c < cPixels; c++) { byte color = reader.ReadByte(); byteArray[i] = color; i++; } } System.Runtime.InteropServices.Marshal.Copy(byteArray, 0, bmpData.Scan0, 1024); bmp.UnlockBits(bmpData); bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); if (!System.IO.Directory.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), "Sprites\\"))) { System.IO.Directory.CreateDirectory(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), "Sprites\\")); } bmp.Save(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), "Sprites\\" + a.ToString() + ".bmp")); bmp.Dispose(); } } }
public string BytesToString(byte[] buff) { string pack = null; System.IO.MemoryStream ms = new System.IO.MemoryStream(buff); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); ushort datasize = br.ReadUInt16(); ushort opcode = br.ReadUInt16(); br.ReadUInt16(); pack = String.Format("{0}->{1}", opcode.ToString("X2"), Decode.StringToPack(br.ReadBytes(datasize))); return pack; }
public Cursors_v2(string path) { System.IO.BinaryReader stream = new System.IO.BinaryReader(new System.IO.FileStream(path + "system\\icons.ph", System.IO.FileMode.Open, System.IO.FileAccess.Read)); if (stream.ReadUInt32() != 0x6e6f6369 || stream.ReadUInt16() != 1) throw new Exception("Invalid icon file"); _numCursors = stream.ReadUInt16(); cursors = new V2_Cursor[_numCursors]; for (int i = 0; i < _numCursors; i++) { readCursor(i, stream); } }
public static MachineType GetDllMachineType(this string dllPath) { // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx // Offset to PE header is always at 0x3C. // The PE header starts with "PE\0\0" = 0x50 0x45 0x00 0x00, // followed by a 2-byte machine type field (see the document above for the enum). // using (var fs = new System.IO.FileStream(dllPath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) using (var br = new System.IO.BinaryReader(fs)) { MachineType machineType = MachineType.IMAGE_FILE_MACHINE_UNKNOWN; // bool isgood = false; try { fs.Seek(0x3c, System.IO.SeekOrigin.Begin); Int32 peOffset = br.ReadInt32(); fs.Seek(peOffset, System.IO.SeekOrigin.Begin); UInt32 peHead = br.ReadUInt32(); if (peHead != 0x00004550) // "PE\0\0", little-endian throw new Exception("Can't find PE header"); machineType = (MachineType)br.ReadUInt16(); // isgood = true; } catch { // isgood = false; } finally { br.Close(); fs.Close(); } return machineType; } }
static void ExtractPIC(string filename) { using (System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(filename))) { ushort width = (ushort)(reader.ReadUInt16() + 2); ushort height = (ushort)(reader.ReadUInt16() + 2); Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); bmp.Palette = colorPalette; System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); byte[] byteArray = new byte[width * height]; for (int x = 1; x < (height - 1); x++) { for (int y = 1; y < (width - 1); y++) { byteArray[(width * x) + y] = reader.ReadByte(); } } System.Runtime.InteropServices.Marshal.Copy(byteArray, 0, bmpData.Scan0, width * height); bmp.UnlockBits(bmpData); bmp.Save(filename.Substring(0, filename.IndexOf(".")) + ".bmp"); bmp.Dispose(); } }
public TerrainData(System.IO.Stream stream, Vector3 worldSize, int size) { Size = size; WorldSize = worldSize; Data = new ushort[size * size]; using (var reader = new System.IO.BinaryReader(stream)) { var i = 0; while (reader.BaseStream.Position < reader.BaseStream.Length) Data[i++] = reader.ReadUInt16(); } }
/// <summary>Checks whether a specified file is a valid Win32 plugin.</summary> /// <param name="file">The file to check.</param> /// <returns>Whether the file is a valid Win32 plugin.</returns> private static bool CheckWin32Header(string file) { using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) { if (reader.ReadUInt16() != 0x5A4D) { /* Not MZ signature */ return false; } stream.Position = 0x3C; stream.Position = reader.ReadInt32(); if (reader.ReadUInt32() != 0x00004550) { /* Not PE signature */ return false; } if (reader.ReadUInt16() != 0x014C) { /* Not IMAGE_FILE_MACHINE_I386 */ return false; } } } return true; }
public string GenerateString(int len) { if (len > 4000) len = 4000; var buffer = new byte[len * 2]; new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(buffer); using (var stream = new System.IO.MemoryStream(buffer, 0, buffer.Length, false, false)) using (var reader = new System.IO.BinaryReader(stream)) { var builder = new System.Text.StringBuilder(buffer.Length, buffer.Length); while (len-- > 0) { var i = (reader.ReadUInt16() & 8) % PWD_CHARSET.Length; builder.Append(PWD_CHARSET[i]); } return builder.ToString(); } }
protected override void GameInitialize() { app.IsFixedTimeStep = true; app.TargetElapsedTime = TimeSpan.FromMilliseconds(10); byte[] tmp = ResourceManager.ReadAllBytes("timeless_table.bin"); var ms = new System.IO.MemoryStream(tmp); var br = new System.IO.BinaryReader(ms); SuperSecretTable = new ushort[tmp.Length / 2]; for(int i=0;i<SuperSecretTable.Length;i++) SuperSecretTable[i] = br.ReadUInt16(); SuperSecretBuffer = NewImage(320, 200); SetResolution(320, 200); StaticInitializers(); Autoexec(); }
public void RunProgram(string filename) { ClearRegisters(); byte Magic1; byte Magic2; byte Magic3; lock (b32Screen1) { b32Screen1.Reset(); } System.IO.BinaryReader br; System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); Magic1 = br.ReadByte(); Magic2 = br.ReadByte(); Magic3 = br.ReadByte(); if (Magic1 != 'B' && Magic2 != '3' && Magic3 != '2') { MessageBox.Show("This is not a valid B32 file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StartAddr = br.ReadUInt16(); ExecAddr = br.ReadUInt16(); ushort Counter = 0; while ((br.PeekChar() != -1)) { byte read = br.ReadByte(); B32Memory[(StartAddr + Counter)] = read; memory.ThreadPoke((ushort)(StartAddr + Counter), read); Counter++; } br.Close(); fs.Close(); InstructionPointer = ExecAddr; pauseProgramToolStripMenuItem.Enabled = true; resumeProgramToolStripMenuItem.Enabled = false; //ExecuteProgram(ExecAddr, Counter); //System.Threading.Thread prog = new System.Threading.Thread(delegate() { ExecuteProgram(ExecAddr, Counter); }); prog = new System.Threading.Thread(delegate() { ExecuteProgram(ExecAddr, Counter); }); PauseEvent = new System.Threading.ManualResetEvent(true); prog.Start(); }
public void Populate(int iOffset, bool useMemoryStream) { this.isNulledOutReflexive = false; System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS); //set offsets BR.BaseStream.Position = iOffset + this.chunkOffset; this.offsetInMap = iOffset + this.chunkOffset; // If we need to read / save tag info directly to file... if (!useMemoryStream) { map.OpenMap(MapTypes.Internal); BR = map.BR; BR.BaseStream.Position = this.offsetInMap; } else this.offsetInMap += meta.offset; switch (ValueType) { case IFPIO.ObjectEnum.Short: { this.Value = BR.ReadInt16(); break; } case IFPIO.ObjectEnum.Int: { this.Value = BR.ReadInt32(); break; } case IFPIO.ObjectEnum.UShort: { this.Value = BR.ReadUInt16(); break; } case IFPIO.ObjectEnum.UInt: { this.Value = BR.ReadUInt32(); break; } case IFPIO.ObjectEnum.Float: { this.Value = BR.ReadSingle(); break; } case IFPIO.ObjectEnum.Unknown: { this.Value = BR.ReadSingle(); break; } case IFPIO.ObjectEnum.Byte: { this.Value = BR.ReadByte(); break; } } // ...and then close the file once we are done! if (!useMemoryStream) map.CloseMap(); if (this.ValueType != IFPIO.ObjectEnum.Unused) this.Controls[1].Text = this.Value.ToString(); }
private void openToolStripMenuItem_Click(object sender, System.EventArgs e) { byte Magic1; byte Magic2; byte Magic3; DialogResult dr; dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.Cancel) return; lock (reallySimpleScreen1) { reallySimpleScreen1.Reset(); } System.IO.BinaryReader br; System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); Magic1 = br.ReadByte(); Magic2 = br.ReadByte(); Magic3 = br.ReadByte(); if (Magic1 != 'B' && Magic2 != '3' && Magic3 != '2') { MessageBox.Show("This is not a valid B32 file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StartAddr = br.ReadUInt16(); ExecAddr = br.ReadUInt16(); ushort Counter = 0; while ((br.PeekChar() != -1)) { ReallySimpleMemory[(StartAddr + Counter)] = br.ReadByte(); Counter++; } br.Close(); fs.Close(); InstructionPointer = ExecAddr; //ExecuteProgram(ExecAddr, Counter); programThread = new Thread(delegate () { ExecuteProgram(ExecAddr, Counter); }); PauseEvent = new ManualResetEvent(true); programThread.Start(); }
public void Populate(int iOffset, bool useMemoryStream) { this.isNulledOutReflexive = false; System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS); //set offsets BR.BaseStream.Position = iOffset + this.chunkOffset; this.offsetInMap = iOffset + this.chunkOffset; // If we need to read / save tag info directly to file... if (!useMemoryStream) { map.OpenMap(MapTypes.Internal); BR = map.BR; BR.BaseStream.Position = this.offsetInMap; } else this.offsetInMap += meta.offset; //Decide how big the bitmask is switch (this.bitCount) { case 8: { this.value = BR.ReadByte(); break; } case 16: { this.value = BR.ReadUInt16(); break; } case 32: { this.value = BR.ReadUInt32(); break; } } // ...and then close the file once we are done! if (!useMemoryStream) map.CloseMap(); //convert this.value (an object) into a bool array, then update the checkboxes with that bool array BitsToBool(); BoolsToControls(); }
private void readGameData() { textBox2.Text = path; if (roq != null) roq.stop(); roq = null; if (vdx != null) vdx.stop(); vdx = null; switch (game) { case GameID.T7G: lblGame.Text = "The 7th Guest"; System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(path); System.IO.FileInfo[] files = DI.GetFiles("*.rl"); this.gjdChooser.Items.Clear(); foreach (System.IO.FileInfo rl in files) { this.gjdChooser.Items.Add(rl.Name); } break; case GameID.T11H: lblGame.Text = "The 11th Hour"; //ROQ roq = new ROQ(new System.IO.BinaryReader(new System.IO.FileStream(path + "\\media\\final_hr.rol", System.IO.FileMode.Open))); this.gjdChooser.Items.Clear(); System.IO.BinaryReader idx = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\groovie\\gjd.gjd", System.IO.FileMode.Open)); string name = ""; while (idx.BaseStream.Position < idx.BaseStream.Length) { if (idx.PeekChar() == 0x0A) { idx.ReadChar(); if (name.Length > 0) this.gjdChooser.Items.Add(name.Substring(0, name.IndexOf(" "))); name = ""; } else name += "" + idx.ReadChar(); } idx.Close(); V2_RL = new List<GJD.RLData>[this.gjdChooser.Items.Count]; for (int i = 0; i < V2_RL.Length; i++) V2_RL[i] = new List<GJD.RLData>(); this.gjdChooser.Items.Add("Icons"); idx = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\groovie\\dir.rl", System.IO.FileMode.Open)); uint ctr = 0; while (idx.BaseStream.Position < idx.BaseStream.Length) { // Get RL content GJD.RLData rl = new GJD.RLData(); idx.ReadUInt32(); rl.offset = idx.ReadUInt32(); rl.length = idx.ReadUInt32(); rl.number = ctr; ctr++; ushort target = idx.ReadUInt16(); byte[] filename; filename = idx.ReadBytes(12); rl.filename = System.Text.Encoding.ASCII.GetString(filename).Trim(); idx.ReadBytes(6); V2_RL[target].Add(rl); } break; default: lblGame.Text = "None"; break; } }
public static void DeserializeVoxelAreaCompactData (byte[] bytes, VoxelArea target) { #if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes); System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); int width = reader.ReadInt32(); int depth = reader.ReadInt32(); if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")"); if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")"); CompactVoxelCell[] cells = new CompactVoxelCell[reader.ReadInt32()]; CompactVoxelSpan[] spans = new CompactVoxelSpan[reader.ReadInt32()]; int[] areas = new int[reader.ReadInt32()]; for (int i=0;i<cells.Length;i++) { cells[i].index = reader.ReadUInt32(); cells[i].count = reader.ReadUInt32(); } for (int i=0;i<spans.Length;i++) { spans[i].con = reader.ReadUInt32(); spans[i].h = reader.ReadUInt32(); spans[i].reg = reader.ReadInt32(); spans[i].y = reader.ReadUInt16(); } for (int i=0;i<areas.Length;i++) { areas[i] = reader.ReadInt32(); } target.compactCells = cells; target.compactSpans = spans; target.areaTypes = areas; #else throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST"); #endif }
private void LoadFile(string filename) { int dataOffset = 0; if (System.IO.File.Exists(filename) == false) { return; } System.IO.BinaryReader fileA; try { System.IO.FileStream fsA = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); fileA = new System.IO.BinaryReader(fsA); } catch (System.ApplicationException) { return; } dataOffset = fileA.ReadInt16() + 2; List<DaxHeaderEntry> headers = new List<DaxHeaderEntry>(); const int headerEntrySize = 9; for (int i = 0; i < ((dataOffset - 2) / headerEntrySize); i++) { DaxHeaderEntry dhe = new DaxHeaderEntry(); dhe.id = fileA.ReadByte(); dhe.offset = fileA.ReadInt32(); dhe.rawSize = fileA.ReadInt16(); dhe.compSize = fileA.ReadUInt16(); headers.Add(dhe); } foreach (DaxHeaderEntry dhe in headers) { byte[] comp = new byte[dhe.compSize]; byte[] raw = new byte[dhe.rawSize]; fileA.BaseStream.Seek(dataOffset + dhe.offset, System.IO.SeekOrigin.Begin); comp = fileA.ReadBytes(dhe.compSize); Decode(dhe.rawSize, dhe.compSize, raw, comp); entries.Add(dhe.id, raw); } fileA.Close(); }
private void LoadProgram() { var fileStream = new System.IO.FileStream(programFileName, System.IO.FileMode.Open); var binaryReader = new System.IO.BinaryReader(fileStream); var magicWordBytes = binaryReader.ReadBytes(8); var magicWord = System.Text.Encoding.Default.GetString(magicWordBytes); if (magicWord != "ZHANGSHU") { System.Windows.Forms.MessageBox.Show("It is NOT a VM binary file!", "Error!", MessageBoxButtons.OK); return; } var offset = binaryReader.ReadUInt16(); var length = binaryReader.ReadUInt16(); var position = binaryReader.ReadUInt16(); //where the program starts in memory ushort i = 0; while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length) { memory[(UInt16)(position + i)] = binaryReader.ReadByte(); ++i; } binaryReader.Close(); fileStream.Close(); programPosition = (UInt16)(position + offset - 14); }
public void Populate(int iOffset, int iIndexedReflexiveOffset) { this.isNulledOutReflexive = false; System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS); int mapMetaOffset = meta.offset; if (this._EntIndex.reflexiveTagType + this._EntIndex.reflexiveTagName != string.Empty) { int tagNum = map.Functions.ForMeta.FindByNameAndTagType(this._EntIndex.reflexiveTagType, this._EntIndex.reflexiveTagName); if (tagNum != -1) { Meta meta2 = new Meta(map); map.OpenMap(MapTypes.Internal); meta2.ReadMetaFromMap(tagNum, true); map.CloseMap(); mapMetaOffset = meta2.offset; this._EntIndex.reflexiveLayer = "root"; } } if (this._EntIndex.reflexiveLayer.ToLower() == "root") this._IndexedReflexiveOffset = mapMetaOffset + this._EntIndex.ReflexiveOffset; else if (this._EntIndex.reflexiveLayer.ToLower() == "oneup") this._IndexedReflexiveOffset = iIndexedReflexiveOffset + this._EntIndex.ReflexiveOffset; /* bool openedMap = false; if (map.isOpen == false) { map.OpenMap(MapTypes.Internal); openedMap = true; } map.BA.Position = iOffset + this.chunkOffset; */ BR.BaseStream.Position = iOffset + this.chunkOffset; this.offsetInMap = meta.offset + iOffset + this.chunkOffset; switch (_ValueType) { case IFPIO.ObjectEnum.Short: { this.Value = (int)BR.ReadInt16(); break; } case IFPIO.ObjectEnum.Int: { this.Value = BR.ReadInt32(); break; } case IFPIO.ObjectEnum.UShort: { this.Value = (int)BR.ReadUInt16(); break; } case IFPIO.ObjectEnum.UInt: { this.Value = (int)BR.ReadUInt32(); break; } case IFPIO.ObjectEnum.Byte: { this.Value = (int)BR.ReadByte(); break; } } UpdateSelectionList(false); /* if (openedMap == true) map.CloseMap(); */ }
public VoxelModel LoadVoxelModel(System.IO.Stream stream, out Vector3 pivot, IProgressListener progress) { var reader = new System.IO.BinaryReader(stream); { var buf = new byte[4]; if (stream.Read(buf, 0, 4) < 4) { throw new System.IO.IOException("Magic not read"); } if (buf[0] != 'K' || buf[1] != 'v' || buf[2] != 'x' || buf[3] != 'l') { throw new System.IO.IOException("Invalid magic"); } } int xsiz = reader.ReadInt32(); int ysiz = reader.ReadInt32(); int zsiz = reader.ReadInt32(); float xpivot = reader.ReadSingle(); float ypivot = reader.ReadSingle(); float zpivot = reader.ReadSingle(); int numblocks = reader.ReadInt32(); var blocks = new Kv6Block[numblocks]; progress?.Report("Reading voxels"); for (int i = 0; i < blocks.Length; ++i) { blocks[i].color = reader.ReadUInt32(); blocks[i].zpos = (int) reader.ReadUInt16(); reader.ReadUInt16(); // skip visFaces & lighting if (((i & 8191) == 0)) { progress?.Report((double)i / blocks.Length * 0.5); } } var xyoffset = new int[xsiz * ysiz]; // skip xoffset for (int i = 0; i < xsiz; ++i) { reader.ReadInt32(); } for (int i = 0; i < xyoffset.Length; ++i) { xyoffset[i] = (int) reader.ReadUInt16(); } progress?.Report("Placing voxels"); int pos = 0; var model = new VoxelModel(xsiz, ysiz, zsiz); for (int x = 0; x < xsiz; ++x) { for (int y = 0; y < ysiz; ++y) { int sb = xyoffset[x * ysiz + y]; for (int i = 0; i < sb; ++i) { var b = blocks[pos]; model[x, y, b.zpos] = b.color; pos += 1; } } progress?.Report((double)pos / blocks.Length * 0.5 + 0.5); } pivot = new Vector3(xpivot, ypivot, zpivot); return model; }
public override void LoadData(System.IO.FileStream __fsFileStream) { System.IO.BinaryReader _brdrReader = new System.IO.BinaryReader(__fsFileStream); // only read necessary params from file header __fsFileStream.Seek(42, System.IO.SeekOrigin.Begin); int _iXDimension = (int)_brdrReader.ReadInt16(); __fsFileStream.Seek(108, System.IO.SeekOrigin.Begin); DataType _dtDataType = (DataType)_brdrReader.ReadInt16(); __fsFileStream.Seek(656, System.IO.SeekOrigin.Begin); int _iYDimension = (int)_brdrReader.ReadInt16(); __fsFileStream.Seek(1446, System.IO.SeekOrigin.Begin); UInt32 numframes = (UInt32)_brdrReader.ReadInt32(); // Start reading the XCalibStruct. SpeCalib XCalib = new SpeCalib(0, 0); __fsFileStream.Seek(3000, System.IO.SeekOrigin.Begin); XCalib.Offset = (double)_brdrReader.ReadDouble(); __fsFileStream.Seek(3008, System.IO.SeekOrigin.Begin); XCalib.Factor = (double)_brdrReader.ReadDouble(); __fsFileStream.Seek(3016, System.IO.SeekOrigin.Begin); XCalib.current_unit = (char)_brdrReader.ReadChar(); __fsFileStream.Seek(3098, System.IO.SeekOrigin.Begin); XCalib.CalibValid = (char)_brdrReader.ReadChar(); __fsFileStream.Seek(3101, System.IO.SeekOrigin.Begin); XCalib.PolynomOrder = (char)_brdrReader.ReadChar(); __fsFileStream.Seek(3263, System.IO.SeekOrigin.Begin); XCalib.PolynomCoeff[0] = _brdrReader.ReadDouble(); XCalib.PolynomCoeff[1] = _brdrReader.ReadDouble(); XCalib.PolynomCoeff[2] = _brdrReader.ReadDouble(); XCalib.PolynomCoeff[3] = _brdrReader.ReadDouble(); XCalib.PolynomCoeff[4] = _brdrReader.ReadDouble(); XCalib.PolynomCoeff[5] = _brdrReader.ReadDouble(); __fsFileStream.Seek(3311, System.IO.SeekOrigin.Begin); XCalib.LaserPosition = (double)_brdrReader.ReadDouble(); // Start reading the YCalibStruct. SpeCalib YCalib = new SpeCalib(0, 0); __fsFileStream.Seek(3489, System.IO.SeekOrigin.Begin); // move ptr to x_calib start YCalib.Offset = (double)_brdrReader.ReadDouble(); __fsFileStream.Seek(3497, System.IO.SeekOrigin.Begin); YCalib.Factor = (double)_brdrReader.ReadDouble(); __fsFileStream.Seek(3505, System.IO.SeekOrigin.Begin); YCalib.current_unit = (char)_brdrReader.ReadChar(); __fsFileStream.Seek(3587, System.IO.SeekOrigin.Begin); YCalib.CalibValid = (char)_brdrReader.ReadChar(); __fsFileStream.Seek(3590, System.IO.SeekOrigin.Begin); YCalib.PolynomOrder = (char)_brdrReader.ReadChar(); __fsFileStream.Seek(3752, System.IO.SeekOrigin.Begin); YCalib.PolynomCoeff[0] = _brdrReader.ReadDouble(); YCalib.PolynomCoeff[1] = _brdrReader.ReadDouble(); YCalib.PolynomCoeff[2] = _brdrReader.ReadDouble(); YCalib.PolynomCoeff[3] = _brdrReader.ReadDouble(); YCalib.PolynomCoeff[4] = _brdrReader.ReadDouble(); YCalib.PolynomCoeff[5] = _brdrReader.ReadDouble(); __fsFileStream.Seek(3800, System.IO.SeekOrigin.Begin); YCalib.LaserPosition = (double)_brdrReader.ReadDouble(); int _iDimension; SpeCalib _calCurrCalib; if (_iYDimension == 1) { _iDimension = _iXDimension; _calCurrCalib = XCalib; } else if (_iXDimension == 1) { _iDimension = _iYDimension; _calCurrCalib = YCalib; } else { throw new UnexpectedFormatException("xylib does not support 2-D images"); } __fsFileStream.Seek(4100, System.IO.SeekOrigin.Begin); // move ptr to frames-start for (int frm = 0; frm < (int)numframes; frm++) { Block _blkBlock = new Block(); Column _colXCol = this.GetCalibColumn(_calCurrCalib, _iDimension); _blkBlock.AddColumn(_colXCol, "", true); ListColumn _colYCol = new ListColumn(); for (int i = 0; i < _iDimension; ++i) { double _dYVal = 0; switch (_dtDataType) { case DataType.SPE_DATA_FLOAT: _dYVal = (double)_brdrReader.ReadSingle(); break; case DataType.SPE_DATA_LONG: _dYVal = (double)_brdrReader.ReadInt32(); break; case DataType.SPE_DATA_INT: _dYVal = (double)_brdrReader.ReadInt16(); break; case DataType.SPE_DATA_UINT: _dYVal = (double)_brdrReader.ReadUInt16(); break; default: break; } _colYCol.AddValue(_dYVal); } _blkBlock.AddColumn(_colYCol, "", true); this.m_blcklstBlocks.Add(_blkBlock); } }
//Чтение TAP и добавление файлов в проект private void LoadTapFile(string filename) { try { System.IO.BinaryReader file = new System.IO.BinaryReader(new System.IO.FileStream(filename,System.IO.FileMode.Open)); while (file.BaseStream.Position<file.BaseStream.Length) { int LEN = file.ReadUInt16(); byte[] Bytes = file.ReadBytes(LEN); //Собственно загрузка, в C# она простая и быстрая //Добавляем загруженную коллекцию байтов в проект Project.Add(Bytes); } file.Close(); } catch { Editor.Error("Произошла ошибка при открытии файла."); } }
public static Row Deserialize(byte[] bytes) { using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) { using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) { byte[] columnSet = BR.ReadBytes (32); int FieldCount = BR.ReadInt32 (); object[] fields = new object[FieldCount]; ColumnSet cs = css [columnSet]; if (cs.Columns.Length != fields.Length) throw new Exception (); for (int n = 0; n != fields.Length; n++) { bool Null = BR.ReadBoolean (); if (Null) { fields [n] = null; continue; } switch (cs.Columns [n].TFQN) { case "System.Byte[]": fields [n] = BR.ReadBytes (BR.ReadInt32 ()); break; case "System.Byte": fields [n] = BR.ReadByte (); break; case "System.SByte": fields [n] = BR.ReadSByte (); break; case "System.Int16": fields [n] = BR.ReadInt16 (); break; case "System.UInt16": fields [n] = BR.ReadUInt16 (); break; case "System.Int32": fields [n] = BR.ReadInt32 (); break; case "System.UInt32": fields [n] = BR.ReadUInt32 (); break; case "System.Int64": fields [n] = BR.ReadInt64 (); break; case "System.UInt64": fields [n] = BR.ReadUInt64 (); break; case "System.Single": fields [n] = BR.ReadSingle (); break; case "System.Double": fields [n] = BR.ReadDouble (); break; case "System.String": fields [n] = BR.ReadString (); break; case "System.Char": fields [n] = BR.ReadChar (); break; case "System.Boolean": fields [n] = BR.ReadBoolean (); break; case "System.DateTime": fields [n] = new DateTime (BR.ReadInt64 ()); break; case "System.Guid": fields [n] = new Guid (BR.ReadBytes (16)); break; } } return new Row (cs, fields); } } }
// TODO: re-add encryption private void BeginReceiveCallback(IAsyncResult ar) { Queue<Action> actionQueue = new Queue<Action>(); try { TcpClient lEndPoint = EndPoint; Thread.MemoryBarrier(); if (lEndPoint == null) { ("NoEndPoint for " + this.DisplayName).Log(); fragmentBuffer = new byte[0]; return; } int cb = lEndPoint.Client.EndReceive(ar); if (cb == 0) { //Disconnect(); return; } byte[] receiveBuffer = ar.AsyncState as byte[]; if (fragmentBuffer.Length > 0) { var temp = new byte[cb + fragmentBuffer.Length]; fragmentBuffer.CopyTo(temp, 0); Array.ConstrainedCopy(receiveBuffer, 0, temp, fragmentBuffer.Length, cb); fragmentBuffer = new byte[0]; receiveBuffer = temp; } else { var temp = new byte[cb]; Array.ConstrainedCopy(receiveBuffer, 0, temp, 0, cb); receiveBuffer = temp; } //("MCNC: receiveBuffer=" + System.Text.Encoding.ASCII.GetString(receiveBuffer)).Log(); var stream = new System.IO.MemoryStream(receiveBuffer); using (var reader = new System.IO.BinaryReader(stream)) { while (stream.Position < stream.Length && stream.ReadByte() == 0x1b) { var lastReadPosition = stream.Position - 1; object o = null; try { var len = reader.ReadUInt16(); byte[] payload = new byte[len]; stream.Read(payload, 0, payload.Length); using (var payloadStream = new System.IO.MemoryStream(payload)) { o = Serializer.ReadObject(payloadStream); } } catch (Exception ex) { //("MCNC: lastReadPosition=" + lastReadPosition + " currentPosition=" + stream.Position).Log(); ex.Log(); // TODO: log/debug exception types thrown here, not documented on MSDN and it's not clear how to handle a buffer underrun in ReadObject // TODO: if the exception is due to an unknown type, the fragmentBuffer logic will result in a deadlock on the network (always retrying a bad object) o = null; } if (o == null) { stream.Seek(lastReadPosition, System.IO.SeekOrigin.Begin); fragmentBuffer = new byte[stream.Length - lastReadPosition]; stream.Read(fragmentBuffer, 0, fragmentBuffer.Length); break; } else { EnqueueAction(actionQueue, o); } } } if (actionQueue.Count == 0) { ("NoActions for " + this.DisplayName).Log(); return; } #region process action queue while (actionQueue.Count > 0) { Action action = actionQueue.Dequeue(); if (action != null) { try { action(); } catch (Exception ex) { ex.Log(); } } } #endregion process action queue } catch (SocketException) { Disconnect(); } catch (ObjectDisposedException) { Disconnect(); } catch (Exception ex) { ex.Log(); } finally { StartReceiving(); } }
void TZXload(string filename) { try { System.IO.BinaryReader file = new System.IO.BinaryReader(new System.IO.FileStream(filename, System.IO.FileMode.Open)); file.ReadBytes(10); //10 байт какой-то херни в начале файла while (file.BaseStream.Position < file.BaseStream.Length) { file.ReadBytes(3); //3 байта какой-то херни в начале каждого блока int LEN = file.ReadUInt16(); byte[] Bytes = file.ReadBytes(LEN); //Собственно загрузка, в C# она простая и быстрая //Добавляем загруженную коллекцию байтов в проект Project.Add(Bytes); } file.Close(); } catch { Editor.Error("Произошла ошибка при открытии файла."); } }