Seek() публичный Метод

public Seek ( int offset, SeekOrigin origin ) : long
offset int
origin SeekOrigin
Результат long
        public void MessageShouldBeSameAfterSerializationAndDeserialization()
        {
            var writer = new BinaryWriter(new MemoryStream());
            IMessageFactory msgFactory = new MessageFactory(new Message[]
                {
                    new ISomeServiceComplexRequest()
                });

            var fixture = new Fixture();
            fixture.Customize<ISomeServiceComplexRequest>(ob =>
                ob.With(x => x.datas,
                    fixture.CreateMany<SubData>().ToList()));
            fixture.Customize<ComplexData>(ob => ob
                .With(x => x.SomeArrString, fixture.CreateMany<string>().ToList())
                .With(x => x.SomeArrRec, fixture.CreateMany<SubData>().ToList()));

            var msg = fixture.CreateAnonymous<ISomeServiceComplexRequest>();

            //serialize and deserialize msg1
            msg.Serialize(writer);
            writer.Seek(0, SeekOrigin.Begin);
            var reader = new BinaryReader(writer.BaseStream);
            Message retMsg = msgFactory.Deserialize(reader);

            retMsg.Should().BeOfType<ISomeServiceComplexRequest>();
            msg.ShouldBeEqualTo((ISomeServiceComplexRequest)retMsg);
        }
Пример #2
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, (short) Tradelist.ItemsByTabs.Count);
            WriteB(writer, "2000B008B8030080000E"); //2000 mb shift?
            WriteD(writer, (int) DateTime.Now.Ticks);
            WriteH(writer, 0x3EC0); // ???
            WriteH(writer, 0);

            WriteB(writer, "7B14AE47E17A843F");

            foreach (KeyValuePair<int, List<int>> tab in Tradelist.ItemsByTabs)
            {
                WriteH(writer, (short) writer.BaseStream.Length);
                WriteH(writer, 0); //next tab shift

                WriteH(writer, (short) tab.Value.Count);
                WriteH(writer, (short) (writer.BaseStream.Length + 6)); //first item shift
                WriteD(writer, tab.Key); // name Id

                writer.Seek((int) writer.BaseStream.Length - 10, SeekOrigin.Begin);
                WriteH(writer, (short) (writer.BaseStream.Length + tab.Value.Count*8));
                writer.Seek(0, SeekOrigin.End);

                for (int i = 0; i < tab.Value.Count; i++)
                {
                    short nowItemShift = (short) writer.BaseStream.Length;
                    WriteH(writer, nowItemShift); //now item shift
                    WriteH(writer, (short) (i == tab.Value.Count - 1 ? 0 : nowItemShift + 8)); //next item shift
                    WriteD(writer, tab.Value[i]);
                }
            }
        }
Пример #3
0
        public void Query(string strAddress, ushort unPort)
        {
            // Build the packet.
            byte[] byPacket = new byte[PT_ASKINFO_SIZE];
            BinaryWriter bw = new BinaryWriter(new MemoryStream(byPacket));

            bw.Seek(4, SeekOrigin.Begin);		// Skip the checksum.
            bw.Write((byte)0);					// ack
            bw.Write((byte)0);					// ackreturn
            bw.Write((byte)PT_ASKINFO);			// Packet type.
            bw.Write((byte)0);					// Reserved.
            bw.Write((byte)0);					// Version. This is actually unnecessary -- the client will reply anyway. -MattW_CFI
            bw.Write((byte)0);					// Reserved.
            bw.Write((byte)0);					// Reserved.
            bw.Write((byte)0);					// Reserved.
            // Time for ping calculation.
            bw.Write(unchecked((uint)(DateTime.Now.Ticks / 10000)));

            // Calculate the checksum.
            bw.Seek(0, SeekOrigin.Begin);
            bw.Write(SRB2Checksum(byPacket));

            // Send the packet.
            udpclient.Send(byPacket, byPacket.Length, strAddress, unPort);
        }
Пример #4
0
        public override void Write(BinaryWriter writer)
        {
            if (TestNpcHex != null)
            {
                WriteB(writer, TestNpcHex);
                return;
            }

            WriteD(writer, 0); //???
            WriteH(writer, 0); //Shit shift

            WriteUid(writer, Npc);
            WriteUid(writer, Npc.Target);
            WriteF(writer, Npc.Position.X);
            WriteF(writer, Npc.Position.Y);
            WriteF(writer, Npc.Position.Z);
            WriteH(writer, Npc.Position.Heading);
            WriteD(writer, 12); //???
            WriteD(writer, Npc.SpawnTemplate.NpcId);
            WriteH(writer, Npc.SpawnTemplate.Type);
            WriteD(writer, 0); //ModelId

            WriteB(writer, "000000000500000001010100000000000000000000000000000000000000");

            WriteUid(writer, Npc.Target); //If 1 agressiv

            WriteB(writer, "000000000000000000");

            writer.Seek(8, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length); //Shit shift
            writer.Seek(0, SeekOrigin.End);

            WriteB(writer, "45C5C8B958C72000E4C2D8D5B4CC0000"); //Shit
        }
Пример #5
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, 0); //Name shift
            WriteH(writer, 0); //Details shift
            WriteH(writer, (short) Player.PlayerData.Details.Length); //Details length

            WriteD(writer, Player.PlayerData.SexRaceClass);
            WriteUid(writer, Player);

            WriteD(writer, 11); //???

            WriteD(writer, Player.PlayerId);
            WriteB(writer, "000000000100000000460000006E000000");
            WriteB(writer, Player.PlayerData.Data); //PlayerData
            WriteC(writer, 1); //Online?
            WriteC(writer, 0); //??
            WriteD(writer, Player.GetLevel()); //Level

            WriteB(writer, "00000000000001000000000000000000");
            WriteQ(writer, Player.Exp);
            WriteQ(writer, Player.GetExpShown());
            WriteQ(writer, Player.GetExpNeed());
            WriteB(writer, "0000000000000000461600000000000000000000");

            WriteD(writer, Player.Inventory.GetItemId(1) ?? 0); //Item (hands)
            WriteD(writer, Player.Inventory.GetItemId(3) ?? 0); //Item (body)
            WriteD(writer, Player.Inventory.GetItemId(4) ?? 0); //Item (gloves)
            WriteD(writer, Player.Inventory.GetItemId(5) ?? 0); //Item (shoes)
            WriteD(writer, 0); //Item (???)
            WriteD(writer, 0); //Item (???)

            WriteB(writer, "5E10C101000000000100000000000000000000000000000000000000000000000000000000");

            WriteD(writer, Player.Inventory.GetItem(1) != null ? Player.Inventory.GetItem(1).Color : 0);
            WriteD(writer, Player.Inventory.GetItem(3) != null ? Player.Inventory.GetItem(3).Color : 0);
            WriteD(writer, Player.Inventory.GetItem(4) != null ? Player.Inventory.GetItem(4).Color : 0);
            WriteD(writer, Player.Inventory.GetItem(5) != null ? Player.Inventory.GetItem(5).Color : 0);
            WriteD(writer, 0); //Item ???
            WriteD(writer, 0); //Item ???

            WriteB(writer, "0001000000000000000000000000");

            writer.Seek(4, SeekOrigin.Begin);
            WriteH(writer, (short) (writer.BaseStream.Length)); //Name shift
            writer.Seek(0, SeekOrigin.End);

            WriteS(writer, Player.PlayerData.Name);

            writer.Seek(6, SeekOrigin.Begin);
            WriteH(writer, (short) (writer.BaseStream.Length)); //Details shift
            writer.Seek(0, SeekOrigin.End);

            WriteB(writer, Player.PlayerData.Details);

            //1603
            //C300D5002000 7A270000 87170B0000800002          7D900000000000000100000000460000006E000000650C00070D0F0400010001000000000000000000010000000000000000000100000000000000010000000000000048030000000000000000000000000000461600000000000000000000162700009C3A00009D3A00009E3A0000                  AD3F1C0F00000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000                            41006C006500680061006E006400720000000C0B10021710090A151910001006100008100C0C10150C101010160C0E100F15

            //1725
            //DC00E4002000 FE2A0000 D2340B0000800000 0B000000 A7250000000000000100000000460000006E0000006503040102050400010001000000000000000000010000000000000000000100000000000000010000000000000048030000000000000000000000000000A30100000000000000000000162700009C3A00009D3A00009E3A0000 0000000000000000 16DBB70300000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000 45006C00610000000601020700000000180F1A00010000000F0001000000000F1517101019100909
        }
Пример #6
0
        public override void Write(BinaryWriter writer)
        {
            //B2C0 0000000000000000 0ECE020000800B00 734F633F 00000000 09000000 00000000000000000000000000000000401F000005000000
            //B2C0 0100380000000000 F042030000800B00 F734423E 00000000 09000000 00000000000000000000000000000000401F000005000000 38000000E02A0900E803000001000000

            lock (Creature.EffectsLock)
            {
                WriteH(writer, (short) Creature.Effects.Count);
                int effectShift = (int) writer.BaseStream.Position;
                WriteH(writer, 0); //first Abnormal shift
                WriteD(writer, 0); //unk
                WriteUid(writer, Creature);
                WriteF(writer, (Creature.LifeStats.Hp/(Creature.MaxHp/100F))/100F);
                WriteD(writer, 0);
                WriteD(writer, Creature.GetLevel()); //npc level
                WriteB(writer, "00000000000000000000000000000000401F000005000000".ToBytes()); // ololo o_O

                for (int i = 0; i < Creature.Effects.Count; i++)
                {
                    writer.Seek(effectShift, SeekOrigin.Begin);
                    WriteH(writer, (short) writer.BaseStream.Length);
                    writer.Seek(0, SeekOrigin.End);

                    WriteH(writer, (short) writer.BaseStream.Length);
                    effectShift = (int) writer.BaseStream.Position;
                    WriteH(writer, 0); //posible next Abnormal shift
                    WriteD(writer, Creature.Effects[i].Abnormality.Id);
                    WriteD(writer, Creature.Effects[i].TimeRemain);
                    WriteD(writer, 1);
                }
            }
        }
Пример #7
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteH(writer, (int)(Npc.Target as Player).UID);
            WriteH(writer, 0);                   // skill id
            WriteD(writer, Attack.Results[0]);   // Damage 1

            WriteD(writer, Attack.Results[1]);   // Damage 2
            WriteD(writer, Attack.Results[2]);   // Damage 3
            WriteD(writer, Attack.Results[3]);   // Damage 4
            WriteD(writer, Attack.Results[4]);   // Damage 5
            WriteD(writer, 0);                   // skill id

            WriteD(writer, Attack.AttackAction); // FLD_EFFERT
            WriteF(writer, Npc.Position.X);
            WriteF(writer, Npc.Position.Z);
            WriteF(writer, Npc.Position.Y);
            WriteC(writer, 4);
            WriteC(writer, (byte)Attack.Count); // The number of attacks

            WriteH(writer, 0);
            WriteD(writer, Npc.Target.LifeStats.Hp); // Finally blood
            WriteD(writer, 0);
            WriteD(writer, 0);
            WriteD(writer, 0);
            WriteD(writer, 0);
            WriteD(writer, 0);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)Npc.UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #8
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, (short) FlyTeleports.Count);
            WriteH(writer, 8);

            for (int i = 0; i < FlyTeleports.Count; i++)
            {
                WriteH(writer, (short)writer.BaseStream.Length);

                short shift = (short) writer.BaseStream.Length;
                WriteH(writer, 0);

                WriteD(writer, FlyTeleports[i].Id);
                WriteD(writer, FlyTeleports[i].Cost);
                WriteD(writer, FlyTeleports[i].FromNameId);
                WriteD(writer, FlyTeleports[i].ToNameId);
                WriteD(writer, FlyTeleports[i].Level);

                if(FlyTeleports.Count >= i+1)
                {
                    writer.Seek(shift, SeekOrigin.Begin);
                    WriteH(writer, (short) writer.BaseStream.Length);
                    writer.Seek(0, SeekOrigin.End);
                }
            }
        }
Пример #9
0
        // Conversion extracted from the sample voice_synthesis.cs (RSSDK\framework\CSharp\voice_synthesis.cs)
        // To understand a little bit more about the WAV file format, acess the following links: 
        //     - http://www-mmsp.ece.mcgill.ca/documents/AudioFormats/WAVE/WAVE.html
        //     - http://www.sonicspot.com/guide/wavefiles.html
        public static void Play(PXCMAudio.AudioData audioData, PXCMAudio.AudioInfo audioInfo) {
            using (var memoryStream = new MemoryStream()) {
                using (var bw = new BinaryWriter(memoryStream)) {
                    bw.Write(0x46464952);  // chunkIdRiff:'FFIR'
                    bw.Write(0);           // chunkDataSizeRiff
                    bw.Write(0x45564157);  // riffType:'EVAW'
                    bw.Write(0x20746d66);  // chunkIdFmt:' tmf'
                    bw.Write(0x12);        // chunkDataSizeFmt
                    bw.Write((short)1);         // compressionCode
                    bw.Write((short)audioInfo.nchannels);  // numberOfChannels
                    bw.Write(audioInfo.sampleRate);   // sampleRate
                    bw.Write(audioInfo.sampleRate * 2 * audioInfo.nchannels); // averageBytesPerSecond
                    bw.Write((short)(audioInfo.nchannels * 2));   // blockAlign
                    bw.Write((short)16);        // significantBitsPerSample
                    bw.Write((short)0);         // extraFormatSize
                    bw.Write(0x61746164);  // chunkIdData:'atad'
                    bw.Write(0);           // chunkIdSizeData

                    bw.Write(audioData.ToByteArray());
                    long pos = bw.Seek(0, SeekOrigin.Current);
                    bw.Seek(0x2a, SeekOrigin.Begin); // chunkDataSizeData
                    bw.Write((int)(pos - 46));
                    bw.Seek(0x04, SeekOrigin.Begin); // chunkDataSizeRiff
                    bw.Write((int)(pos - 8));
                    bw.Seek(0, SeekOrigin.Begin);

                    using (var soundPlayer = new SoundPlayer(memoryStream)) {
                        soundPlayer.PlaySync();
                    }
                }
            }
        }
Пример #10
0
        //public SpPartyAbnormals(Player player) // WRONG
        //{
        //    Player = player;
        //}
        public override void Write(BinaryWriter writer)
        {
            WriteD(writer, 0);
            WriteH(writer, (short) Player.Effects.Count);
            WriteH(writer, 0); //first effect shift
            WriteD(writer, 11); //hello AGAIN, f*****g 0x0b shit...how are you? -_-
            WriteD(writer, Player.PlayerId);

            writer.Seek(10, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            for (int i = 0; i < Player.Effects.Count; i++)
            {
                short shPos = (short) writer.BaseStream.Position;

                WriteH(writer, shPos);
                WriteH(writer, 0); //next abnormal
                WriteD(writer, 0);
                WriteD(writer, 0);
                WriteC(writer, 1); //possible IsBuff

                if (Player.Effects.Count > i + 1)
                {
                    writer.Seek(shPos + 2, SeekOrigin.Begin);
                    WriteH(writer, (short) writer.BaseStream.Length);
                    writer.Seek(0, SeekOrigin.End);
                }
            }
        }
Пример #11
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, 0); //Sender shift
            WriteH(writer, 0); //Message shift
            WriteD(writer, Type.GetHashCode());

            WriteUid(writer, Player);

            byte isGm = 0;

            if (Player != null)
                isGm = (byte)(Communication.Global.AdminEngine.IsGM(Player) ? 1 : 0);

            WriteC(writer, 0); //Blue shit
            WriteC(writer, isGm); //GM

            if (Player != null)
            {
                writer.Seek(4, SeekOrigin.Begin);
                WriteH(writer, (short) writer.BaseStream.Length);
                writer.Seek(0, SeekOrigin.End);

                WriteS(writer, Player.PlayerData.Name);
            }

            writer.Seek(6, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteS(writer, Message);

            WriteC(writer, 0);
        }
Пример #12
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteB(writer, Data);

            writer.Seek(4, SeekOrigin.Begin);
            WriteH(writer, Opcode);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #13
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteC(writer, (byte)Id);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)Player.UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #14
0
 public static void GenericInject(string Filename, int Offset, byte[] Data, int Length)
 {
     BinaryWriter BW = new BinaryWriter(File.OpenWrite(Filename));
     BW.Seek(Offset, SeekOrigin.Begin);
     BW.Write(new byte[Length], 0, Length);
     BW.Seek(Offset, SeekOrigin.Begin);
     BW.Write(Data);
     BW.Close();
 }
Пример #15
0
        public override void Write(BinaryWriter writer)
        {
            WriteWord(writer, 0); // shift
            WriteUid(writer, Npc);

            writer.Seek(4, SeekOrigin.Begin);
            WriteWord(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteString(writer, Options);
        }
Пример #16
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteD(writer, 1);
            WriteD(writer, Count);
            WriteD(writer, MaxCount);
            WriteD(writer, 1);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)Player.UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #17
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, 0); //name shift
            WriteD(writer, 11);
            WriteD(writer, Player.PlayerId);

            writer.Seek(4, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteS(writer, Player.PlayerData.Name);
        }
 private void WriteCues(BinaryWriter w)
 {
     // write the cue chunks to the end of the stream
     if (cues != null)
     {
         byte[] cueChunks = cues.GetRIFFChunks();
         int cueChunksSize = cueChunks.Length;
         w.Seek(0, SeekOrigin.End);
         w.Write(cues.GetRIFFChunks(), 0, cueChunksSize);
         w.Seek(4, SeekOrigin.Begin);
         w.Write((int)(w.BaseStream.Length - 8));
     }
 }
Пример #19
0
 public static void WriteToFile(DataUnit dataPage, BinaryWriter writer)
 {
     long initPos = writer.Seek(100L + (dataPage.UnitID * 0x1000L));
     writer.Write((byte) dataPage.Type);
     writer.Write(dataPage.NextUnitID);
     writer.Write(dataPage.IsEmpty);
     writer.Write(dataPage.DataBlockLength);
     if (!dataPage.IsEmpty)
     {
         writer.Seek(initPos + 8L);
         writer.Write(dataPage.DataBlock, 0, dataPage.DataBlockLength);
     }
 }
Пример #20
0
        public override void Write(BinaryWriter writer)
        {
            WriteD(writer, 0); //guild name start shift
            WriteD(writer, 0); //member level start shift
            WriteD(writer, 0); //member level end shift
            WriteD(writer, 0); //possible guildlogo shift
            WriteUid(writer, Player);

            writer.Seek(4, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteS(writer, GuildName);

            writer.Seek(6, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteS(writer, GuildMemberLevel);

            writer.Seek(8, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteH(writer, 0);

            writer.Seek(10, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteH(writer, 0);
        }
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, 6); // craft skill counter?
            WriteH(writer, 0); //first skill shift
            WriteD(writer, 0);
            WriteH(writer, 1);
            WriteH(writer, 0); //craft skills end shift
            WriteB(writer, "009A0100000D000000");

            writer.Seek(6, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            int i = 0;
            foreach (var skill in Player.PlayerCraftStats.CraftSkillCollection)
            {
                i++;

                short position = (short) writer.BaseStream.Length;

                WriteH(writer, position);
                WriteH(writer, 0); //next skill shift
                WriteD(writer, skill.Key.GetHashCode());
                WriteD(writer, skill.Key.GetHashCode());
                WriteD(writer, skill.Value);

                if (i < Player.PlayerCraftStats.CraftSkillCollection.Count)
                {
                    writer.Seek(position + 2, SeekOrigin.Begin);
                    WriteH(writer, (short) writer.BaseStream.Length);
                    writer.Seek(0, SeekOrigin.End);
                }
            }

            i = 0;
            writer.Seek(14, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            foreach (var extractSkill in Player.PlayerCraftStats.ExtractSkillCollection)
            {
                i++;

                short position = (short) writer.BaseStream.Length;

                WriteH(writer, position);
                WriteH(writer, 0); //next skill shift
                WriteD(writer, extractSkill.Key.GetHashCode());
                WriteD(writer, extractSkill.Key.GetHashCode());
                WriteD(writer, extractSkill.Value);

                if (i < Player.PlayerCraftStats.ExtractSkillCollection.Count)
                {
                    writer.Seek(position + 2, SeekOrigin.Begin);
                    WriteH(writer, (short) writer.BaseStream.Length);
                    writer.Seek(0, SeekOrigin.End);
                }
            }
        }
Пример #22
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteF(writer, Creature.Position.X);
            WriteF(writer, Creature.Position.Y);
            WriteF(writer, Creature.Position.Z);

            WriteD(writer, -1);
            WriteD(writer, MoveStyle);
            WriteF(writer, Creature.Position.X);
            WriteD(writer, (Creature as Npc).LifeStats.Hp);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)(Creature as Npc).UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #23
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteD(writer, 0);

            writer.Seek(2, SeekOrigin.Begin);
            if (Creature is Player)
            {
                WriteH(writer, (int)(Creature as Player).UID);
            }
            else if (Creature is Npc)
            {
                WriteH(writer, (int)(Creature as Npc).UID);
            }
            writer.Seek(0, SeekOrigin.End);
        }
Пример #24
0
        public override void Write(BinaryWriter writer)
        {
            WriteWord(writer, 0); //name shift
            WriteDword(writer, Friend.PlayerId);
            WriteDword(writer, Friend.GetLevel());
            WriteDword(writer, Friend.PlayerData.Race.GetHashCode());
            WriteDword(writer, Friend.PlayerData.Class.GetHashCode());
            WriteByte(writer, "0100000001000000020000000700000000");

            writer.Seek(4, SeekOrigin.Begin);
            WriteWord(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteString(writer, Friend.PlayerData.Name);
        }
Пример #25
0
        public override void Write(BinaryWriter writer)
        {
            WriteWord(writer, (short) (VisualEffect != null ? VisualEffect.Times.Count : 0)); //count of timesteps
            int timesShift = (int) writer.BaseStream.Position;
            WriteWord(writer, 0); //shift

            WriteUid(writer, Creature); //attacker uniqueid
            WriteUid(writer, Target); //target unique id

            WriteDword(writer, Creature.GetModelId());
            WriteDword(writer, SkillId + 0x4000000);
            WriteLong(writer, 0);
            WriteDword(writer, AttackUid);

            WriteDword(writer, 0);

            WriteDword(writer, Damage); //damage ;)
            WriteDword(writer, AttackType); // 1 - Normal, 65537 - Critical
            WriteByte(writer, 0);

            if (VisualEffect != null)
            {
                WriteSingle(writer, VisualEffect.Position.X);
                WriteSingle(writer, VisualEffect.Position.Y);
                WriteSingle(writer, VisualEffect.Position.Z);
                WriteWord(writer, VisualEffect.Position.Heading);

                WriteDword(writer, VisualEffect.Type.GetHashCode());
                WriteDword(writer, 0);
                WriteDword(writer, AttackUid);

                foreach (int time in VisualEffect.Times)
                {
                    writer.Seek(timesShift, SeekOrigin.Begin);
                    WriteWord(writer, (short) writer.BaseStream.Length);
                    writer.Seek(0, SeekOrigin.End);

                    WriteWord(writer, (short) writer.BaseStream.Position);
                    timesShift = (int) writer.BaseStream.Position;
                    WriteWord(writer, 0);

                    WriteDword(writer, time);
                    WriteByte(writer, "0000803F0000803F000080BF");
                }
            }
            else
                WriteByte(writer, new byte[27]); //unk
        }
Пример #26
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, (short) ShoppingCart.BuyItems.Count);
            short buyItemShift = (short) writer.BaseStream.Position;
            WriteH(writer, 0); //first buyitem shift

            WriteH(writer, (short) ShoppingCart.SellItems.Count);
            short sellItemShift = (short) writer.BaseStream.Position;
            WriteH(writer, 0); //first sellitem shift

            WriteUid(writer, Player);
            WriteD(writer, ShoppingCart.Uid);
            WriteQ(writer, 0);
            WriteQ(writer, ShoppingCart.GetBuyItemsPrice());
            WriteB(writer, "9A9999999999A93F"); // shit from traidlist
            WriteQ(writer, ShoppingCart.GetSellItemsPrice());

            foreach (var item in ShoppingCart.BuyItems)
            {
                writer.Seek(buyItemShift, SeekOrigin.Begin);
                WriteH(writer, (short) writer.BaseStream.Length);
                writer.Seek(0, SeekOrigin.End);

                WriteH(writer, (short) writer.BaseStream.Position);
                buyItemShift = (short) writer.BaseStream.Position;
                WriteH(writer, 0);

                WriteD(writer, item.ItemTemplate.Id);
                WriteD(writer, item.Count);
            }

            foreach (var item in ShoppingCart.SellItems)
            {
                writer.Seek(sellItemShift, SeekOrigin.Begin);
                WriteH(writer, (short) writer.BaseStream.Length);
                writer.Seek(0, SeekOrigin.End);

                WriteH(writer, (short) (writer.BaseStream.Length));
                sellItemShift = (short) writer.BaseStream.Position;
                WriteH(writer, 0);

                WriteD(writer, item.ItemTemplate.Id);
                WriteD(writer, item.Count);
                WriteD(writer, 0);
                WriteD(writer, 0);
                WriteH(writer, 0);
            }
        }
Пример #27
0
        private static string ExtractFile(string path, string fileName = null)
        {
            var stream = _assembly.GetManifestResourceStream($"{_assemblyName}.Resources.{path}");
            if (stream == null)
            {
                return null;

            }
            string dest;

            if (string.IsNullOrEmpty(fileName))
                dest = Path.GetTempFileName() + System.IO.Path.GetExtension(path);
            else
                dest = System.IO.Path.Combine(Path.GetTempPath(), fileName);

            using (var writer = new BinaryWriter(File.Open(dest, FileMode.OpenOrCreate)))
            {
                writer.Seek(0, SeekOrigin.Begin);
                int n;
                byte[] buffer = new byte[4096];
                while ((n = stream.Read(buffer, 0, 4096)) > 0)
                {
                    writer.Write(buffer, 0, n);
                }
            }
            return dest;
        }
Пример #28
0
 public CSendBlock(MemoryStream data, uint start, uint end, byte[] FileHash, ref ArrayList UploadDataPackets)
 {
     MemoryStream buffer;
     uint size;
     BinaryReader reader = new BinaryReader(data);
     BinaryWriter writer;
     //byte[] aux_buffer;
     while (start != end)
     {
         buffer = new MemoryStream();
         writer = new BinaryWriter(buffer);
         DonkeyHeader header = new DonkeyHeader((byte)Protocol.ClientCommand.SendingPart, writer);
         writer.Write(FileHash);
         if (end - start > 10240) size = 10240;
         else size = end - start;
         writer.Write(start);
         writer.Write(start + size);
         //aux_buffer=reader.ReadBytes((int)size);
         //writer.Write(aux_buffer);
         writer.Write(reader.ReadBytes((int)size));
         start += size;
         header.Packetlength = (uint)writer.BaseStream.Length - header.Packetlength + 1;
         writer.Seek(0, SeekOrigin.Begin);
         header.Serialize(writer);
         UploadDataPackets.Add(buffer);
         writer = null;
         buffer = null;
     }
     reader.Close();
     data.Close();
     data = null;
     reader = null;
 }
Пример #29
0
        // taken from https://stackoverflow.com/a/57254324
        public static Icon ConvertToIco(Image img, int size)
        {
            Icon icon;

            using (var msImg = new System.IO.MemoryStream())
                using (var msIco = new System.IO.MemoryStream())
                {
                    img.Save(msImg, System.Drawing.Imaging.ImageFormat.Png);
                    using (var bw = new System.IO.BinaryWriter(msIco))
                    {
                        bw.Write((short)0);          //0-1 reserved
                        bw.Write((short)1);          //2-3 image type, 1 = icon, 2 = cursor
                        bw.Write((short)1);          //4-5 number of images
                        bw.Write((byte)size);        //6 image width
                        bw.Write((byte)size);        //7 image height
                        bw.Write((byte)0);           //8 number of colors
                        bw.Write((byte)0);           //9 reserved
                        bw.Write((short)0);          //10-11 color planes
                        bw.Write((short)32);         //12-13 bits per pixel
                        bw.Write((int)msImg.Length); //14-17 size of image data
                        bw.Write(22);                //18-21 offset of image data
                        bw.Write(msImg.ToArray());   // write image data
                        bw.Flush();
                        bw.Seek(0, SeekOrigin.Begin);
                        icon = new Icon(msIco);
                    }
                }
            return(icon);
        }
Пример #30
0
        public CServerHello(MemoryStream buffer)
        {
            DonkeyHeader header;
            BinaryWriter writer=new BinaryWriter(buffer);
            header=new DonkeyHeader((byte)Protocol.ServerCommand.LoginRequest,writer);
            writer.Write(CKernel.Preferences.GetByteArray("UserHash"));
            writer.Write(CKernel.Preferences.GetUInt("ID"));
            writer.Write(CKernel.Preferences.GetUShort("TCPPort"));
            uint nParameters=5;
            writer.Write(nParameters);
            // user
            new ParameterWriter((byte)Protocol.ClientParameter.Name,CKernel.Preferences.GetString("UserName"),writer);
            // version
            new ParameterWriter((byte)Protocol.ClientParameter.Version,Protocol.EDONKEYVERSION,writer);
            // port
            new ParameterWriter((byte)Protocol.ClientParameter.Port,(uint)CKernel.Preferences.GetUShort("TCPPort"),writer);
            // compression
            new ParameterWriter((byte)Protocol.ClientParameter.Compression,5,writer); //1 (supports compression) + 5 (supports alternative server ports)
            // emule version
            new ParameterWriter((byte)Protocol.ClientParameter.EmuleVersion,Protocol.EMULE_VERSION_COMPLEX,writer);

            header.Packetlength=(uint)writer.BaseStream.Length-header.Packetlength+1;
            writer.Seek(0,SeekOrigin.Begin);
            header.Serialize(writer);
        }
Пример #31
0
        public void AddMarkerReq(Card card, Guid id, string name, ushort count, ushort origCount, bool isScriptChange)
        {
            //Log.Info("[ProtOut] AddMarkerReq");

            if(Program.Client == null)return;
            MemoryStream stream = new MemoryStream(512);
            stream.Seek(4, SeekOrigin.Begin);
            BinaryWriter writer = new BinaryWriter(stream);

              if (Program.Client.Muted != 0)
              writer.Write(Program.Client.Muted);
              else
              writer.Write(0);
            writer.Write((byte)59);
            writer.Write(card.Id);
            writer.Write(id.ToByteArray());
            writer.Write(name);
            writer.Write(count);
            writer.Write(origCount);
            writer.Write(isScriptChange);

            writer.Flush(); writer.Seek(0, SeekOrigin.Begin);
            writer.Write((int)stream.Length);
            writer.Close();
            Send(stream.ToArray());
        }
 public void save(string filePath)
 {
     FileStream fileStream = new FileStream(filePath, FileMode.Create);
     BinaryWriter writer = new BinaryWriter(fileStream);
     writer.Write(header.sGroupID.ToCharArray());
     writer.Write(header.dwFileLength);
     writer.Write(header.sRiffType.ToCharArray());
     writer.Write(format.sChunkID.ToCharArray());
     writer.Write(format.dwChunkSize);
     writer.Write(format.wFormatTag);
     writer.Write(format.wChannels);
     writer.Write(format.dwSamplesPerSec);
     writer.Write(format.dwAvgBytesPerSec);
     writer.Write(format.wBlockAlign);
     writer.Write(format.wBitsPerSample);
     writer.Write(data.sChunkID.ToCharArray());
     writer.Write(data.dwChunkSize);
     foreach (short dataPoint in data.shortArray)
     {
         writer.Write(dataPoint);
     }
     writer.Seek(4, SeekOrigin.Begin);
     uint filesize = (uint)writer.BaseStream.Length;
     writer.Write(filesize - 8);
     writer.Close();
     fileStream.Close();
 }
Пример #33
0
        static void InitializeHeader(BinaryReader br, BinaryWriter bw)
        {
            bw.Seek(0, SeekOrigin.Begin);

            for (var i = 0; i < 36; i++)
                bw.Write(br.ReadByte());

            const string compare = "data";

            try
            {
                for (var i = 0; i < 4; i++)
                {
                    var b = br.ReadByte();
                    if (b != compare[i])
                        throw  new Exception("ERROR Subchunk2ID");
                    bw.Write(b);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            for (var i = 0; i < 4; i++)
                bw.Write(br.ReadByte());
        }
Пример #34
0
        private void button3_Click(object sender, EventArgs e)
        {
            var invertedList = new List<short>();
            listBox1.Items.Clear();
            button1.Text = short.MaxValue.ToString();
            using (var reader = new BinaryReader(File.Open(@"d:\xxx\wh", FileMode.OpenOrCreate)))
            {
                using (var writer = new BinaryWriter(File.Open(@"d:\xxx\wh.correct", FileMode.OpenOrCreate)))
                {
                    writer.Seek(0, SeekOrigin.Begin);
                    while (reader.BaseStream.Position < reader.BaseStream.Length)
                    {
                        var i = reader.ReadInt16();
                        int i2;
                        //if (i < 0) i2 = i + short.MaxValue; // ne takhle to je blbe
                        //else i2 = i - short.MaxValue;
                        i2 = i*-1; // obratit znaminko
                        var i3 = Convert.ToInt16(i2);
                        invertedList.Add(i3);
                        listBox1.Items.Add(i + ":" + i2 + ":" + i3);
                        //writer.Write(i3);
                    }
                    button2.Text = listBox1.Items.Count.ToString();
                    for (int i4 = invertedList.Count-1; i4 >= 0; i4--)
                    {
                        // zapsat soubor LIFO
                        writer.Write(invertedList[i4]);
                    }

                }
            }

            MessageBox.Show("a");
        }
Пример #35
0
        public override void Write(BinaryWriter writer)
        {
            WriteH(writer, 0); //name start shift
            WriteD(writer, Type);
            WriteD(writer, Player.PlayerData.SexRaceClass);
            WriteD(writer, Player.GetLevel());

            WriteH(writer, 1);
            WriteH(writer, 11);

            writer.Seek(4, SeekOrigin.Begin);
            WriteH(writer, (short) writer.BaseStream.Length);
            writer.Seek(0, SeekOrigin.End);

            WriteS(writer, Player.PlayerData.Name);
        }
Пример #36
0
 public CMuleHello(MemoryStream buffer, bool isResponse)
 {
     BinaryWriter writer = new BinaryWriter(buffer);
     DonkeyHeader header;
     if (isResponse)
         header = new DonkeyHeader((byte)Protocol.ClientCommandExt.eMuleInfoAnswer, writer, Protocol.ProtocolType.eMule);
     else
         header = new DonkeyHeader((byte)Protocol.ClientCommandExt.eMuleInfo, writer, Protocol.ProtocolType.eMule);
     writer.Write(Protocol.EMULE_VERSION);
     writer.Write(Protocol.EMULE_PROTOCOL_VERSION);
     uint nParameters = 8;
     writer.Write(nParameters);
     // compression
     new ParameterWriter(Protocol.ET_COMPRESSION, Protocol.EMULE_VERSION_COMPRESION, writer);
     // udp port
     new ParameterWriter(Protocol.ET_UDPPORT, (uint)CKernel.Preferences.GetUShort("UDPPort"), writer);
     // version udp
     new ParameterWriter(Protocol.ET_UDPVER, (uint)Protocol.EMULE_VERSION_UDP, writer);
     // version source exchange
     new ParameterWriter(Protocol.ET_SOURCEEXCHANGE, (uint)Protocol.EMULE_VERSION_SOURCEEXCHANGE, writer);
     // version comments
     new ParameterWriter(Protocol.ET_COMMENTS, (uint)Protocol.EMULE_VERSION_COMMENTS, writer);
     // version extended requests
     new ParameterWriter(Protocol.ET_EXTENDEDREQUEST, (uint)Protocol.EMULE_VERSION_EXTENDEDREQUEST, writer);
     // client compatible
     new ParameterWriter(Protocol.ET_COMPATIBLECLIENT, (byte)Protocol.Client.Hathi, writer);
     // version Hathi
     new ParameterWriter(Protocol.ET_ELEPHANTVERSION, Protocol.ELEPHANT_VERSION, writer);
     header.Packetlength = (uint)writer.BaseStream.Length - header.Packetlength + 1;
     writer.Seek(0, SeekOrigin.Begin);
     header.Serialize(writer);
 }
Пример #37
0
 public CCancelTransfer(MemoryStream buffer)
 {
     BinaryWriter writer = new BinaryWriter(buffer);
     DonkeyHeader header = new DonkeyHeader((byte)Protocol.ClientCommand.CancelTransfer, writer);
     header.Packetlength = (uint)writer.BaseStream.Length - header.Packetlength + 1;
     writer.Seek(0, SeekOrigin.Begin);
     header.Serialize(writer);
 }
Пример #38
0
        public static void Main(string[] args)
        {
            // Read input file
            string inputFilePath  = getInputFilePath(args);
            string outputFilePath = getOutputFilePath(args);

            Console.WriteLine("Input file: {0}", inputFilePath);
            Console.WriteLine("Output file: {0}", outputFilePath);

            // Initialize values
            LabelTable       = new System.Collections.Hashtable(50);
            CurrentNdx       = 0;
            AsLength         = 0;
            ExecutionAddress = 0;
            IsEnd            = false;
            SourceProgram    = "";

            AsLength = Convert.ToUInt16("0", 16);

            System.IO.BinaryWriter output;
            System.IO.TextReader   input;
            System.IO.FileStream   fs = new System.IO.FileStream(outputFilePath, System.IO.FileMode.Create);
            output = new System.IO.BinaryWriter(fs);
            input  = System.IO.File.OpenText(inputFilePath);

            string[] lines = input.ReadToEnd().Split('\n');
            input.Close();

            // Remove commented lines (the ones that start with "#")
            for (int i = 0; i < lines.Length; ++i)
            {
                string cLine = lines [i];
                if (cLine.StartsWith("#"))
                {
                    continue;
                }
                SourceProgram += cLine + "\n";
            }

            // Magic header
            output.Write('B');
            output.Write('I');
            output.Write('Z');

            // Starting address
            output.Write(Convert.ToUInt16("0", 16));
            output.Write((ushort)0);

            // Convert to byte code
            Parse(output);

            output.Seek(5, System.IO.SeekOrigin.Begin);
            output.Write(ExecutionAddress);

            // Close output stream
            output.Close();
            fs.Close();
        }
Пример #39
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            for (int i = 0; i < 30; i++)
            {
                if (Player.Inventory.EquipItems.ContainsKey(i) && i <= 15)
                {
                    var item = Player.Inventory.GetEquipItem(i);
                    WriteItemInfo(writer, item);
                }
                else
                {
                    WriteB(writer, new byte[88]);
                }
            }

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)Player.UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #40
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteD(writer, 2);

            WriteF(writer, X1);
            WriteF(writer, Z1);
            WriteF(writer, Y1);

            WriteF(writer, X2);
            WriteF(writer, Z2);
            WriteF(writer, Y2);

            WriteD(writer, 1);
            WriteF(writer, Distance);
            WriteD(writer, Target);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)Player.UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #41
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteC(writer, (byte)Type);

            if (IsSystemMessage)
            {
                WriteSN(writer, "System");
            }
            else
            {
                WriteSN(writer, Player.PlayerData.Name);
            }

            WriteB(writer, new byte[7]);
            WriteS(writer, Message);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)((IsSystemMessage) ? 0 : Player.UID));
            writer.Seek(0, SeekOrigin.End);
        }
Пример #42
0
        /// <summary>
        /// WriteData
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="pos"></param>
        public static void WriteData(string fileName, int pos, Byte[] data)
        {
            //Datei öffnen
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            System.IO.BinaryWriter wr = new System.IO.BinaryWriter(fs, Encoding.UTF8);

            //An Schreibposition gehen
            wr.Seek(pos, System.IO.SeekOrigin.Begin);
            //Daten schreiben
            wr.Write(data);
            //Fertig
            wr.Close();
            fs.Close();
        }
Пример #43
0
        public override void Write(System.IO.BinaryWriter writer)
        {
            WriteD(writer, 1);

            WriteH(writer, (int)Npc.UID);
            WriteH(writer, (int)Npc.UID);

            WriteH(writer, Npc.NpcId);

            WriteD(writer, 1);

            WriteD(writer, Npc.LifeStats.Hp);
            WriteD(writer, Npc.MaxHp);

            WriteF(writer, Npc.Position.X);
            WriteF(writer, Npc.Position.Z);
            WriteF(writer, Npc.Position.Y);

            WriteD(writer, 0x40800000);

            WriteF(writer, Npc.SpawnTemplate.Face1);
            WriteF(writer, Npc.SpawnTemplate.Face2);

            WriteF(writer, Npc.Position.X);
            WriteF(writer, Npc.Position.Z);
            WriteF(writer, Npc.Position.Y);

            WriteD(writer, 0);
            WriteD(writer, 0);
            WriteD(writer, 0x0C);
            WriteD(writer, 0);

            writer.Seek(2, SeekOrigin.Begin);
            WriteH(writer, (int)Npc.UID);
            writer.Seek(0, SeekOrigin.End);
        }
Пример #44
0
 static public int Seek(IntPtr l)
 {
     try {
         System.IO.BinaryWriter self = (System.IO.BinaryWriter)checkSelf(l);
         System.Int32           a1;
         checkType(l, 2, out a1);
         System.IO.SeekOrigin a2;
         checkEnum(l, 3, out a2);
         var ret = self.Seek(a1, a2);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #45
0
        public byte[] Serialize()
        {
            try
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream(100);
                using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms))
                {
                    bw.Write((int)CURRENT_VERSION);
                    bw.Write(0);                        // cnt's placeholder

                    bw.Write(_baseModel);

                    int cnt = 0;
                    int n   = _avatarParts.Length;
                    for (int i = 0; i < n; i++)
                    {
                        if (!string.IsNullOrEmpty(_avatarParts[i]))
                        {
                            bw.Write(i);
                            bw.Write((string)_avatarParts[i]);
                            cnt++;
                        }
                    }

                    bw.Seek(sizeof(int), SeekOrigin.Begin);
                    bw.Write(cnt);
                }

                return(ms.ToArray());
            }
            catch (System.Exception e)
            {
                Debug.LogWarning(e);
                return(null);
            }
        }
Пример #46
0
        /// <summary>
        /// Write a set of input files to a torrent7z archive (assuming the same output archive name)
        /// </summary>
        /// <param name="inputFiles">Input files to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the archive was written properly, false otherwise</returns>
        public override bool Write(List <string> inputFiles, string outDir, List <Rom> roms, bool date = false, bool romba = false)
        {
            bool   success  = false;
            string tempFile = Path.Combine(outDir, "tmp" + Guid.NewGuid().ToString());

            // If either list of roms is null or empty, return
            if (inputFiles == null || roms == null || inputFiles.Count == 0 || roms.Count == 0)
            {
                return(success);
            }

            // If the number of inputs is less than the number of available roms, return
            if (inputFiles.Count < roms.Count)
            {
                return(success);
            }

            // If one of the files doesn't exist, return
            foreach (string file in inputFiles)
            {
                if (!File.Exists(file))
                {
                    return(success);
                }
            }

            // Get the output archive name from the first rebuild rom
            string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".7z") ? "" : ".7z"));

            // Set internal variables
            SevenZipBase.SetLibraryPath("7za.dll");
            SevenZipExtractor  oldZipFile;
            SevenZipCompressor zipFile;

            try
            {
                // If the full output path doesn't exist, create it
                if (!Directory.Exists(Path.GetDirectoryName(archiveFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName));
                }

                // If the archive doesn't exist, create it and put the single file
                if (!File.Exists(archiveFileName))
                {
                    zipFile = new SevenZipCompressor()
                    {
                        ArchiveFormat    = OutArchiveFormat.SevenZip,
                        CompressionLevel = CompressionLevel.Normal,
                    };

                    // Map all inputs to index
                    Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), i);
                    }

                    // Sort the keys in TZIP order
                    List <string> keys = inputIndexMap.Keys.ToList();
                    keys.Sort(ZipFile.TorrentZipStringCompare);

                    // Create the temp directory
                    string tempPath = Path.Combine(outDir, Guid.NewGuid().ToString());
                    if (!Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }

                    // Now add all of the files in order
                    foreach (string key in keys)
                    {
                        string newkey = Path.Combine(tempPath, key);

                        File.Move(inputFiles[inputIndexMap[key]], newkey);
                        zipFile.CompressFiles(tempFile, newkey);
                        File.Move(newkey, inputFiles[inputIndexMap[key]]);

                        // After the first file, make sure we're in append mode
                        zipFile.CompressionMode = CompressionMode.Append;
                    }

                    Utilities.CleanDirectory(tempPath);
                    Utilities.TryDeleteDirectory(tempPath);
                }

                // Otherwise, sort the input files and write out in the correct order
                else
                {
                    // Open the old archive for reading
                    using (oldZipFile = new SevenZipExtractor(archiveFileName))
                    {
                        // Map all inputs to index
                        Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                        for (int i = 0; i < inputFiles.Count; i++)
                        {
                            // If the old one contains the new file, then just skip out
                            if (oldZipFile.ArchiveFileNames.Contains(roms[i].Name.Replace('\\', '/')))
                            {
                                continue;
                            }

                            inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), -(i + 1));
                        }

                        // Then add all of the old entries to it too
                        for (int i = 0; i < oldZipFile.FilesCount; i++)
                        {
                            inputIndexMap.Add(oldZipFile.ArchiveFileNames[i], i);
                        }

                        // If the number of entries is the same as the old archive, skip out
                        if (inputIndexMap.Keys.Count <= oldZipFile.FilesCount)
                        {
                            success = true;
                            return(success);
                        }

                        // Otherwise, process the old zipfile
                        zipFile = new SevenZipCompressor()
                        {
                            ArchiveFormat    = OutArchiveFormat.SevenZip,
                            CompressionLevel = CompressionLevel.Normal,
                        };

                        // Get the order for the entries with the new file
                        List <string> keys = inputIndexMap.Keys.ToList();
                        keys.Sort(ZipFile.TorrentZipStringCompare);

                        // Copy over all files to the new archive
                        foreach (string key in keys)
                        {
                            // Get the index mapped to the key
                            int index = inputIndexMap[key];

                            // If we have the input file, add it now
                            if (index < 0)
                            {
                                FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(key, inputStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                            }

                            // Otherwise, copy the file from the old archive
                            else
                            {
                                Stream oldZipFileEntryStream = new MemoryStream();
                                oldZipFile.ExtractFile(index, oldZipFileEntryStream);
                                oldZipFileEntryStream.Seek(0, SeekOrigin.Begin);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(oldZipFile.ArchiveFileNames[index], oldZipFileEntryStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                                oldZipFileEntryStream.Dispose();
                            }

                            // After the first file, make sure we're in append mode
                            zipFile.CompressionMode = CompressionMode.Append;
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                success = false;
            }

            // If the old file exists, delete it and replace
            if (File.Exists(archiveFileName))
            {
                Utilities.TryDeleteFile(archiveFileName);
            }
            File.Move(tempFile, archiveFileName);

            // Now make the file T7Z
            // TODO: Add ACTUAL T7Z compatible code

            BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));

            bw.Seek(0, SeekOrigin.Begin);
            bw.Write(Constants.Torrent7ZipHeader);
            bw.Seek(0, SeekOrigin.End);

            using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
            {
                // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
                byte[] tempsig = Constants.Torrent7ZipSignature;
                if (oldZipFile.FilesCount > 1)
                {
                    tempsig[16] = 0x2;
                }
                else
                {
                    tempsig[16] = 0;
                }

                bw.Write(tempsig);
                bw.Flush();
                bw.Dispose();
            }

            return(true);
        }
Пример #47
0
        private void ReorganiseDirectory(String diskName, String filenameToDelete)
        {
            Byte directoryTrack  = 20;
            Byte directorySector = 4;
            Byte directoryIndex  = 0;

            Byte prevDirTrack  = directoryTrack;
            Byte prevDirSector = directorySector;

            int directoryCount = 0;

            Byte[] directory = new Byte[256];

            for (int index = 0; index < directory.Length; index++)
            {
                directory[index] = 0x00;
            }

            MemoryStream memStream = new System.IO.MemoryStream(directory, 0, directory.Length);
            BinaryWriter bw        = new System.IO.BinaryWriter(memStream);

            memStream.Seek(0x10, SeekOrigin.Begin);

            // Read entire directory
            OricFileInfo[] diskDirectory = ReadDirectory(diskName);

            foreach (OricFileInfo fileInfo in diskDirectory)
            {
                if (!fileInfo.ProgramName.Equals(filenameToDelete))
                {
                    String filename = fileInfo.ProgramName;
                    filename = Path.GetFileNameWithoutExtension(filename);
                    filename = filename.PadRight(9, ' ');

                    bw.Write(filename.ToCharArray());

                    String extension = fileInfo.Extension.PadRight(3, ' ');
                    bw.Write(extension.ToCharArray());

                    bw.Write(fileInfo.FirstTrack);
                    bw.Write(fileInfo.FirstSector);
                    bw.Write((Byte)fileInfo.LengthSectors);

                    if (fileInfo.Protection == OricProgram.ProtectionStatus.Protected)
                    {
                        bw.Write((Byte)0xC0);
                    }
                    else if (fileInfo.Protection == OricProgram.ProtectionStatus.Unprotected)
                    {
                        bw.Write((Byte)0x40);
                    }
                    else
                    {
                        bw.Write((Byte)0x00);
                    }

                    directoryIndex++;

                    if (directoryIndex == 15)
                    {
                        prevDirTrack  = directoryTrack;
                        prevDirSector = directorySector;

                        directoryCount++;

                        // Directory is full, setup details of next directory
                        switch (directoryCount)
                        {
                        case 1: directorySector = 7; break;

                        case 2: directorySector = 10; break;

                        case 3: directorySector = 13; break;

                        case 4: directorySector = 16; break;

                        default:
                            // Find next free sector and use that
                            break;
                        }

                        bw.Seek(0x00, SeekOrigin.Begin);
                        bw.Write(directoryTrack);
                        bw.Write(directorySector);

                        // Write value to indicate directory is full
                        bw.Write((Byte)0x00);

                        base.WriteSector(prevDirTrack, prevDirSector, directory);

                        for (int index = 0; index < directory.Length; index++)
                        {
                            directory[index] = 0x00;
                        }

                        directoryIndex = 0;

                        memStream.Seek(0x10, SeekOrigin.Begin);
                    }
                }
            }

            if (directoryIndex > 0)
            {
                bw.Seek(0x02, SeekOrigin.Begin);

                Byte nextFreeSlot = (Byte)((directoryIndex + 1) * 16);
                bw.Write((Byte)nextFreeSlot);

                base.WriteSector(directoryTrack, directorySector, directory);
            }

            base.WriteDisk();
        }
Пример #48
0
 public long Seek(int _offset, SeekOrigin _origin)
 {
     return(bw.Seek(_offset, _origin));
 }
Пример #49
0
        private void DownLoadFile()
        {
            //临时文件夹
            string tempFolderPath = Path.Combine(_SystemBinUrl, _TempFolder);

            if (!Directory.Exists(tempFolderPath))
            {
                Directory.CreateDirectory(tempFolderPath);
            }

            //总进度条
            if (progressBarTotal.InvokeRequired)
            {
                progressBarTotal.Invoke((ThreadStart) delegate
                {
                    progressBarTotal.Maximum = downloadFileList.Count;
                });
            }

            #region  载文件
            UpdateFileInfo mFileInfo    = null;
            string         fileSavePath = "";
            int            i            = 1;
            foreach (DownloadFileInfo file in this.downloadFileList)
            {
                //正在下载的文件名称
                ShowCurrentlabelText(file.FileName);

                //文件信息
                string filePath = Path.Combine(tempFolderPath, file.FileFullName);
                DirectoryHelper.CreateDirectoryByFilePath(filePath);
                mFileInfo              = new UpdateFileInfo();
                mFileInfo.FileName     = filePath;          //本地文件名,包括路径
                mFileInfo.FileSaveName = file.FileFullName; //要下载的文件名称
                mFileInfo.FileCategory = "";

                //开始下载文件
                mFileInfo = Proxy.DownLoadFile(mFileInfo);
                if (!string.IsNullOrEmpty(mFileInfo.ErrorMessage))
                {
                    ShowCurrentlabelText(mFileInfo.ErrorMessage);
                    break;
                }
                if (mFileInfo != null && mFileInfo.FileData != null && mFileInfo.FileData.Count > 0)
                {
                    fileSavePath = mFileInfo.FileName;
                    while (mFileInfo.Length != mFileInfo.Offset)  //循环的读取文件,上传,直到文件的长度等于文件的偏移量
                    {
                        if (mFileInfo.Offset != 0)
                        {
                            mFileInfo = Proxy.DownLoadFile(mFileInfo);
                        }
                        if (mFileInfo.FileData == null || mFileInfo.FileData.Count < 1)
                        {
                            break;
                        }
                        using (System.IO.FileStream fs = new System.IO.FileStream(fileSavePath, System.IO.FileMode.OpenOrCreate))
                        {
                            long offset = mFileInfo.Offset;                                        //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加
                            using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs)) //初始化文件写入器
                            {
                                writer.Seek((int)offset, System.IO.SeekOrigin.Begin);              //设置文件的写入位置
                                writer.Write(mFileInfo.FileData.ToArray());                        //写入数据

                                mFileInfo.Offset   = fs.Length;                                    //返回追加数据后的文件位置
                                mFileInfo.FileData = null;

                                if (writer != null)
                                {
                                    writer.Close();
                                }
                            }
                            if (fs != null)
                            {
                                fs.Close();
                            }
                        }//end using (System.IO.FileStream fs = new System.IO.FileStream(fileSavePath, System.IO.FileMode.OpenOrCreate))
                        //进度条
                        int percentValue = (int)(((decimal)mFileInfo.Offset / (decimal)mFileInfo.Length) * (decimal)100);
                        if (progressBarCurrent.InvokeRequired)
                        {
                            progressBarCurrent.Invoke((ThreadStart) delegate
                            {
                                progressBarCurrent.Value = percentValue;
                                //System.Threading.Thread.Sleep(300);
                            });
                        }
                    } //end while (mFileInfo.Length != mFileInfo.Offset)
                }     //end if (mFileInfo != null && mFileInfo.FileData != null && mFileInfo.FileData.Count > 0)
                //总进度
                if (progressBarTotal.InvokeRequired)
                {
                    progressBarTotal.Invoke((ThreadStart) delegate
                    {
                        progressBarTotal.Value = i;
                        System.Threading.Thread.Sleep(300);
                    });
                }
                i++;
            }
            if (this.downloadFileList.Count == (i - 1))
            {
                this.downloadFileList.Clear();
            }
            #endregion

            #region 处理下载
            this.Invoke(new MethodInvoker(delegate
            {
                buttonOk.Enabled = false;
            }));
            //Debug.WriteLine("All Downloaded");
            foreach (DownloadFileInfo file in this.allFileList)
            {
                //string tempUrlPath = Utility.GetFolderUrl(file,_SystemBinUrl,_TempFolder);
                string oldPath = string.Empty;
                string newPath = string.Empty;
                try
                {
                    oldPath = Path.Combine(_SystemBinUrl, file.FileFullName);
                    newPath = Path.Combine(_SystemBinUrl + _TempFolder, file.FileFullName);

                    //if (!string.IsNullOrEmpty(tempUrlPath))
                    //{
                    //    oldPath = Path.Combine(_SystemBinUrl + tempUrlPath.Substring(1), file.FileName);
                    //    newPath = Path.Combine(_SystemBinUrl + _TempFolder + tempUrlPath, file.FileName);
                    //}
                    //else
                    //{
                    //    oldPath = Path.Combine(_SystemBinUrl, file.FileName);
                    //    newPath = Path.Combine(_SystemBinUrl + _TempFolder, file.FileName);
                    //}

                    ////just deal with the problem which the files EndsWith xml can not download
                    //System.IO.FileInfo f = new FileInfo(newPath);
                    //if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml"))
                    //{
                    //    ShowErrorAndRestartApplication();
                    //}


                    //Added for dealing with the config file download errors
                    string newfilepath = string.Empty;
                    if (newPath.Substring(newPath.LastIndexOf(".") + 1).Equals("config_"))
                    {
                        if (System.IO.File.Exists(newPath))
                        {
                            if (newPath.EndsWith("_"))
                            {
                                newfilepath = newPath;
                                newPath     = newPath.Substring(0, newPath.Length - 1);
                                oldPath     = oldPath.Substring(0, oldPath.Length - 1);
                            }
                            File.Move(newfilepath, newPath);
                        }
                    }
                    //End added

                    Utility.MoveFolderToOld(oldPath, newPath);

                    //if (File.Exists(oldPath))
                    //{
                    //    Utility.MoveFolderToOld(oldPath, newPath);
                    //}
                    //else
                    //{
                    //    //Edit for config_ file
                    //    if (!string.IsNullOrEmpty(tempUrlPath))
                    //    {
                    //        if (!Directory.Exists(_SystemBinUrl + tempUrlPath.Substring(1)))
                    //        {
                    //            Directory.CreateDirectory(_SystemBinUrl + tempUrlPath.Substring(1));


                    //            Utility.MoveFolderToOld(oldPath, newPath);
                    //        }
                    //        else
                    //        {
                    //            Utility.MoveFolderToOld(oldPath, newPath);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        Utility.MoveFolderToOld(oldPath, newPath);
                    //    }

                    //}
                }
                catch (Exception)
                {
                    //log the error message,you can use the application's log code
                }
            }
            #endregion

            this.allFileList.Clear();

            //下载完成
            if (this.downloadFileList.Count == 0)
            {
                Exit(true);
            }
            else//下载出问题
            {
                Exit(false);
            }
        }
Пример #50
0
        public void Write(System.IO.BinaryWriter bw)
        {
            var oc0 = new OffsetContainer();
            var oc1 = new OffsetContainer();

            bw.Write(ByteOrder);
            bw.Write(Version);
            bw.Write(SystemIdentifier);
            bw.Write(CLSID.ToByteArray());
            bw.Write(NumPropertySets);
            bw.Write(FMTID0.ToByteArray());
            bw.Write(Offset0);

            if (NumPropertySets == 2)
            {
                bw.Write(FMTID1.ToByteArray());
                bw.Write(Offset1);
            }


            oc0.OffsetPS = (int)bw.BaseStream.Position;
            bw.Write(PropertySet0.Size);
            bw.Write(PropertySet0.NumProperties);

            // w property offsets
            for (int i = 0; i < PropertySet0.NumProperties; i++)
            {
                oc0.PropertyIdentifierOffsets.Add(bw.BaseStream.Position); //Offset of 4 to Offset value
                PropertySet0.PropertyIdentifierAndOffsets[i].Write(bw);
            }

            for (int i = 0; i < PropertySet0.NumProperties; i++)
            {
                oc0.PropertyOffsets.Add(bw.BaseStream.Position);
                PropertySet0.Properties[i].Write(bw);
            }

            var padding0 = bw.BaseStream.Position % 4;

            //if (padding0 > 0)
            //{
            //    for (int p = 0; p < padding0; p++)
            //        bw.Write((byte)0);
            //}

            int size0 = (int)(bw.BaseStream.Position - oc0.OffsetPS);



            if (NumPropertySets == 2)
            {
                oc1.OffsetPS = (int)bw.BaseStream.Position;

                bw.Write(PropertySet1.Size);
                bw.Write(PropertySet1.NumProperties);

                // w property offsets
                for (int i = 0; i < PropertySet1.PropertyIdentifierAndOffsets.Count; i++)
                {
                    oc1.PropertyIdentifierOffsets.Add(bw.BaseStream.Position); //Offset of 4 to Offset value
                    PropertySet1.PropertyIdentifierAndOffsets[i].Write(bw);
                }

                for (int i = 0; i < PropertySet1.NumProperties; i++)
                {
                    oc1.PropertyOffsets.Add(bw.BaseStream.Position);
                    PropertySet1.Properties[i].Write(bw);
                }

                int size1 = (int)(bw.BaseStream.Position - oc1.OffsetPS);

                bw.Seek(oc1.OffsetPS + 4, System.IO.SeekOrigin.Begin);
                bw.Write(size1);
            }

            bw.Seek(oc0.OffsetPS, System.IO.SeekOrigin.Begin);
            bw.Write(size0);

            int shiftO1 = 2 + 2 + 4 + 16 + 4 + 16; //OFFSET0

            bw.Seek(shiftO1, System.IO.SeekOrigin.Begin);
            bw.Write(oc0.OffsetPS);

            if (NumPropertySets == 2)
            {
                bw.Seek(shiftO1 + 4 + 16, System.IO.SeekOrigin.Begin);
                bw.Write(oc1.OffsetPS);
            }

            //-----------

            for (int i = 0; i < PropertySet0.PropertyIdentifierAndOffsets.Count; i++)
            {
                bw.Seek((int)oc0.PropertyIdentifierOffsets[i] + 4, System.IO.SeekOrigin.Begin); //Offset of 4 to Offset value
                bw.Write((int)(oc0.PropertyOffsets[i] - oc0.OffsetPS));
            }



            if (PropertySet1 != null)
            {
                for (int i = 0; i < PropertySet1.PropertyIdentifierAndOffsets.Count; i++)
                {
                    bw.Seek((int)oc1.PropertyIdentifierOffsets[i], System.IO.SeekOrigin.Begin); //Offset of 4 to Offset value
                    bw.Write(oc1.PropertyOffsets[i] - oc1.OffsetPS);
                }
            }
        }
Пример #51
0
    public static bool SetBoolValue(string ValueName, bool ValueToSet, string ConfigFileName)
    {
        try
        {
            string SettingsPath = Application.dataPath.Remove(Application.dataPath.LastIndexOf("/")) + "/ProjectSettings/" + ConfigFileName + ".asset";

            System.IO.FileStream   fs;
            System.IO.BinaryReader br;
            fs = System.IO.File.Open(SettingsPath, System.IO.FileMode.Open);
            br = new System.IO.BinaryReader(fs);

            // Read the unsigned int at offset 0x0C in the file.
            // This contains the offset at which the setting's numerical values are stored.
            br.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Begin);

            // For some reason, the offset is Big Endian in the file.
            int SettingsOffset = GetBigEndianIntFromBinaryReader(br);

            // In the file, we start with 0x14 bytes, then a string containing the unity version,
            // then 0x0C bytes, then a string containing the base class name, followed by a string containing "base".
            string tempStr;
            br.BaseStream.Seek(0x14, System.IO.SeekOrigin.Begin);
            tempStr = GetStringFromBinaryReader(br); // Unity Version
            br.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Current);
            tempStr = GetStringFromBinaryReader(br); // Config file Name
            if (tempStr != ConfigFileName)
            {
                // File format has changed, return error
                return(false);
            }

            tempStr = GetStringFromBinaryReader(br); // "Base"
            if (tempStr != "Base")
            {
                // File format has changed, return error
                return(false);
            }

            // This string is then followed by 24 bytes
            br.BaseStream.Seek(24, System.IO.SeekOrigin.Current);

            // We then have a series of String (type), String (variable name), and 24 bytes
            // We can use the type of the settings before the field we are looking for to
            // find its offset after SettingsOffset.
            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                string SettingType = GetStringFromBinaryReader(br);
                string SettingName = GetStringFromBinaryReader(br);

                if (SettingName == ValueName)
                {
                    break;
                }

                br.BaseStream.Seek(24, System.IO.SeekOrigin.Current);

                if (GetSizeofTypeByString(SettingType) == -1)
                {
                    // File format has changed, return error
                    return(false);
                }

                SettingsOffset += GetSizeofTypeByString(SettingType);
            }

            // Set the setting in the file
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
            bw.Seek(SettingsOffset, System.IO.SeekOrigin.Begin);
            bw.Write(ValueToSet ? (byte)1 : (byte)0);
            bw.Close();
            fs.Close();
        }
        catch (Exception)
        {
            // Error happened
            return(false);
        }

        // Success!
        return(true);
    }
Пример #52
0
        static void Main(string[] args)
        {
            if (!parse_args(args))
            {
                show_usage();
                return;
            }

            var d = new System.IO.DirectoryInfo(src_dir);

            var o = new System.IO.BinaryWriter(new System.IO.FileStream(ofname, System.IO.FileMode.Create));


            // Write 32 kiB of zeros to the system area
            o.Write(new byte[32 * 1024]);

            List <VolumeDescriptor> voldescs = new List <VolumeDescriptor>();

            // Add a primary volume descriptor
            var pvd = new PrimaryVolumeDescriptor();

            voldescs.Add(pvd);

            ElToritoBootDescriptor bvd = null;

            if (bootEntries.Count > 0)
            {
                bvd = new ElToritoBootDescriptor();
                voldescs.Add(bvd);
            }

            voldescs.Add(new VolumeDescriptorSetTerminator());

            // Generate directory tree
            List <AnnotatedFSO> files, dirs;
            var afso = AnnotatedFSO.BuildAFSOTree(d, out dirs, out files);

            // Allocate space for files + directories
            int cur_lba = 0x10 + voldescs.Count;

            List <AnnotatedFSO> output_order = new List <AnnotatedFSO>();
            AnnotatedFSO        afso_bc      = null;

            foreach (var file in files)
            {
                if (file.fsi is BootCatalogFileInfo)
                {
                    afso_bc = file;
                    continue;
                }
                var fi   = file.fsi as FileInfo;
                var l    = align(fi.Length);
                var lbal = l / 2048;

                file.lba = cur_lba;
                file.len = (int)fi.Length;
                cur_lba += (int)lbal;

                output_order.Add(file);

                foreach (var bfe in bootEntries)
                {
                    if (bfe.ffname != null && bfe.boot_table && bfe.ffname == fi.FullName)
                    {
                        file.needs_boot_table = true;
                        bfe.afso_boot_file    = file;
                    }
                }
            }

            // create boot catalog
            List <byte> bc     = new List <byte>();
            var         bc_lba = cur_lba;

            if (bootEntries.Count > 0)
            {
                // Validation entry
                List <byte> val_ent = new List <byte>();
                val_ent.Add(0x01);
                if (bootEntries[0].type == BootEntry.BootType.BIOS)
                {
                    val_ent.Add(0);
                }
                else
                {
                    val_ent.Add(0xef);
                }
                val_ent.Add(0);
                val_ent.Add(0);
                //val_ent.AddRange(Encoding.ASCII.GetBytes("isomake".PadRight(24)));
                for (int i = 0; i < 24; i++)
                {
                    val_ent.Add(0);
                }
                var cs = elt_checksum(val_ent, 0xaa55);
                val_ent.Add((byte)(cs & 0xff));
                val_ent.Add((byte)((cs >> 8) & 0xff));
                val_ent.Add(0x55);
                val_ent.Add(0xaa);
                bc.AddRange(val_ent);

                // default entry
                List <byte> def_ent = new List <byte>();
                if (bootEntries[0].bootable)
                {
                    def_ent.Add(0x88);
                }
                else
                {
                    def_ent.Add(0x00);
                }
                switch (bootEntries[0].etype)
                {
                case BootEntry.EmulType.Floppy:
                    def_ent.Add(0x02);
                    break;

                case BootEntry.EmulType.Hard:
                    def_ent.Add(0x04);
                    break;

                case BootEntry.EmulType.NoEmul:
                    def_ent.Add(0x00);
                    break;

                default:
                    throw new NotSupportedException();
                }
                def_ent.AddRange(BitConverter.GetBytes((ushort)bootEntries[0].load_seg));
                def_ent.Add(0x0);
                def_ent.Add(0x0);
                def_ent.AddRange(BitConverter.GetBytes((ushort)bootEntries[0].sector_count));
                if (bootEntries[0].afso_boot_file != null)
                {
                    def_ent.AddRange(BitConverter.GetBytes(bootEntries[0].afso_boot_file.lba));
                }
                else
                {
                    def_ent.AddRange(BitConverter.GetBytes((int)0));
                }
                for (int i = 0; i < 20; i++)
                {
                    def_ent.Add(0);
                }
                bc.AddRange(def_ent);

                for (int idx = 1; idx < bootEntries.Count; idx++)
                {
                    // section header
                    List <byte> sh = new List <byte>();
                    if (idx == bootEntries.Count - 1)
                    {
                        sh.Add(0x91);
                    }
                    else
                    {
                        sh.Add(0x90);
                    }
                    if (bootEntries[idx].type == BootEntry.BootType.BIOS)
                    {
                        sh.Add(0x0);
                    }
                    else
                    {
                        sh.Add(0xef);
                    }
                    sh.AddRange(BitConverter.GetBytes((ushort)1));
                    for (int i = 0; i < 28; i++)
                    {
                        sh.Add(0);
                    }
                    //sh.AddRange(Encoding.ASCII.GetBytes(bootEntries[idx].type.ToString().PadRight(28)));
                    bc.AddRange(sh);

                    // section entry
                    List <byte> se = new List <byte>();
                    if (bootEntries[idx].bootable)
                    {
                        se.Add(0x88);
                    }
                    else
                    {
                        se.Add(0x00);
                    }
                    switch (bootEntries[idx].etype)
                    {
                    case BootEntry.EmulType.Floppy:
                        se.Add(0x02);
                        break;

                    case BootEntry.EmulType.Hard:
                        se.Add(0x04);
                        break;

                    case BootEntry.EmulType.NoEmul:
                        se.Add(0x00);
                        break;

                    default:
                        throw new NotSupportedException();
                    }
                    se.AddRange(BitConverter.GetBytes((ushort)bootEntries[idx].load_seg));
                    se.Add(0);
                    se.Add(0);
                    se.AddRange(BitConverter.GetBytes((ushort)bootEntries[idx].sector_count));
                    if (bootEntries[idx].afso_boot_file != null)
                    {
                        se.AddRange(BitConverter.GetBytes((int)bootEntries[idx].afso_boot_file.lba));
                    }
                    else
                    {
                        se.AddRange(BitConverter.GetBytes((int)0));
                    }
                    se.Add(0);
                    for (int i = 0; i < 19; i++)
                    {
                        se.Add(0);
                    }
                    bc.AddRange(se);
                }

                afso_bc.lba = bc_lba;
                afso_bc.len = bc.Count;

                cur_lba += (int)align(bc.Count) / 2048;
            }

            // create root dir first entry continuation area containing rockridge attribute if required
            rr_ce = new List <byte>();
            if (do_rr)
            {
                // Use a spare sector to contain the 'ER' field as is it too big for the system use area
                // This is later referenced in a 'CE' entry
                rr_ce_lba = cur_lba++;

                // Add SUSP ER field to identify RR
                rr_ce.Add(0x45); rr_ce.Add(0x52); // "ER"
                var ext_id   = "IEEE_P1282";
                var ext_desc = "THE IEEE P1282 PROTOCOL PROVIDES SUPPORT FOR POSIX FILE SYSTEM SEMANTICS.";
                var ext_src  = "PLEASE CONTACT THE IEEE STANDARDS DEPARTMENT, PISCATAWAY, NJ, USA FOR THE P1282 SPECIFICATION.";
                rr_ce.Add((byte)(8 + ext_id.Length + ext_desc.Length + ext_src.Length)); // length
                rr_ce.Add(1);                                                            // version
                rr_ce.Add((byte)ext_id.Length);                                          // LEN_ID
                rr_ce.Add((byte)ext_desc.Length);                                        // LEN_DES
                rr_ce.Add((byte)ext_src.Length);                                         // LEN_SRC
                rr_ce.Add(1);                                                            // EXT_VER
                rr_ce.AddRange(Encoding.ASCII.GetBytes(ext_id));
                rr_ce.AddRange(Encoding.ASCII.GetBytes(ext_desc));
                rr_ce.AddRange(Encoding.ASCII.GetBytes(ext_src));
            }

            // build directory tree from most deeply nested to most shallow, so that we automatically patch up
            //  the appropriate child lbas as we go
            List <byte> dir_tree = new List <byte>();
            var         dt_lba   = cur_lba;
            Dictionary <int, AnnotatedFSO> parent_dir_map = new Dictionary <int, AnnotatedFSO>();

            for (int i = 7; i >= 0; i--)
            {
                var afso_level = afso[i];
                foreach (var cur_afso in afso_level)
                {
                    build_dir_tree(cur_afso, dir_tree, dt_lba, parent_dir_map);
                }
            }

            // patch up parent lbas
            foreach (var kvp in parent_dir_map)
            {
                var lba = kvp.Value.lba;
                var len = kvp.Value.len;

                var lba_b = int_lsb_msb(lba);
                var len_b = int_lsb_msb(len);

                insert_bytes(lba_b, kvp.Key + 2, dir_tree);
                insert_bytes(len_b, kvp.Key + 10, dir_tree);
            }

            // And root directory entry
            var root_entry = build_dir_entry("\0", afso[0][0].lba, afso[0][0].len, d);

            cur_lba += dir_tree.Count / 2048;

            // create path table
            var path_table_l_lba = cur_lba;

            byte[] path_table_l     = build_path_table(afso, true);
            var    path_table_b_lba = path_table_l_lba + (int)align(path_table_l.Length) / 2048;

            byte[] path_table_b = build_path_table(afso, false);

            cur_lba = path_table_b_lba + (int)align(path_table_b.Length) / 2048;

            // Set pvd entries
            pvd.WriteString("VolumeIdentifier", "UNNAMED");
            pvd.WriteInt("VolumeSpaceSize", cur_lba);
            pvd.WriteInt("VolumeSetSize", 1);
            pvd.WriteInt("VolumeSequenceNumber", 1);
            pvd.WriteInt("LogicalBlockSize", 2048);
            pvd.WriteInt("PathTableSize", path_table_l.Length);
            pvd.WriteInt("LocTypeLPathTable", path_table_l_lba);
            pvd.WriteInt("LocTypeMPathTable", path_table_b_lba);
            pvd.WriteBytes("RootDir", root_entry);

            if (bootEntries.Count > 0)
            {
                bvd.BootCatalogAddress = bc_lba;
            }

            // Write out volume descriptors
            foreach (var vd in voldescs)
            {
                vd.Write(o);
            }

            // files
            foreach (var f in output_order)
            {
                o.Seek(f.lba * 2048, SeekOrigin.Begin);
                var fin = new BinaryReader(((FileInfo)f.fsi).OpenRead());

                var b = fin.ReadBytes(f.len);

                if (f.needs_boot_table)
                {
                    // patch in the eltorito boot info table to offset 8

                    // first get 32 bit checksum from offset 64 onwards
                    uint csum = elt_checksum32(b, 64);
                    insert_bytes(BitConverter.GetBytes((int)0x10), 8, b);
                    insert_bytes(BitConverter.GetBytes((int)f.lba), 12, b);
                    insert_bytes(BitConverter.GetBytes((int)f.len), 16, b);
                    insert_bytes(BitConverter.GetBytes(csum), 20, b);
                }

                o.Write(b, 0, f.len);
            }

            // directory records
            o.Seek(dt_lba * 2048, SeekOrigin.Begin);
            o.Write(dir_tree.ToArray(), 0, dir_tree.Count);

            // path tables
            o.Seek(path_table_l_lba * 2048, SeekOrigin.Begin);
            o.Write(path_table_l, 0, path_table_l.Length);
            o.Seek(path_table_b_lba * 2048, SeekOrigin.Begin);
            o.Write(path_table_b, 0, path_table_b.Length);

            // boot catalog
            if (bootEntries.Count > 0)
            {
                o.Seek(bc_lba * 2048, SeekOrigin.Begin);

                o.Write(bc.ToArray(), 0, bc.Count);
            }

            // rr es field continuation area
            if (rr_ce != null)
            {
                o.Seek(rr_ce_lba * 2048, SeekOrigin.Begin);

                o.Write(rr_ce.ToArray(), 0, rr_ce.Count);
            }

            // Align to sector size
            o.Seek(0, SeekOrigin.End);
            while ((o.BaseStream.Position % 2048) != 0)
            {
                o.Write((byte)0);
            }

            // Add 300k padding - required for VirtualBox it seems
            //  According to 'man xorriso':
            //  "This is a traditional remedy for a traditional bug in block device read drivers."
            for (int i = 0; i < 300 * 1024 / 4; i++)
            {
                o.Write((int)0);
            }

            o.Close();
        }