private void RecursiveWriteStream(System.IO.BinaryWriter bw, FileListNode node) { var offset = bw.BaseStream.Position; bw.Write(0); // pad count to write to later var count = 0; for (var child = node.FirstChild; child != null; child = child.Next) { bw.Write(child.Name); bw.Write(child.IsDirectory); bw.Write(child.Length); bw.Write(child.CreationTimeUtc.Ticks); bw.Write(child.LastWriteTimeUtc.Ticks); if (child.IsDirectory) { RecursiveWriteStream(bw, child); } ++count; } bw.Seek((int)offset, System.IO.SeekOrigin.Begin); bw.Write(count); bw.Seek(0, System.IO.SeekOrigin.End); }
public void Complete() { if (zinfoset == false) { throw new Exception("Z information not set - can't complete stream write."); } w_tlg.Write(topvws); w_tlg.Write(botvws); w_tlg.Write(m_toptz); w_tlg.Write(m_topbz); w_tlg.Write(m_bottz); w_tlg.Write(m_botbz); FlushStream(t_topvw); FlushStream(t_botvw); w_tlg.Write(toptks); w_tlg.Write(bottks); w_tlg.Write(linked); FlushStream(t_toptk); FlushStream(t_bottk); FlushStream(t_linked); FlushStream(t_topix); FlushStream(t_botix); long nextpos = w_tlg.BaseStream.Position; w_tlg.Seek((int)Section_Tracks_pos, System.IO.SeekOrigin.Begin); w_tlg.Write(nextpos); w_tlg.Seek(0, System.IO.SeekOrigin.End); w_tlg.Flush(); w_tlg.Close(); Dispose(); }
internal void WriteAt(System.UInt64 value, long position) { var oldPosition = Stream.Position; Writer.Seek((int)position, System.IO.SeekOrigin.Begin); Writer.Write(value); Writer.Seek((int)oldPosition, System.IO.SeekOrigin.Begin); }
/// <summary> /// Creates the elf32 file. /// </summary> /// <param name="compiler">The compiler.</param> private void CreateElf64File(Mosa.Runtime.CompilerFramework.AssemblyCompiler compiler) { using (System.IO.FileStream fs = new System.IO.FileStream(this.OutputFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { Elf64Header header = new Elf64Header(); header.Type = Elf64FileType.Executable; header.Machine = Elf64MachineType.Intel386; header.SectionHeaderNumber = (ushort)(Sections.Count + 2); header.SectionHeaderOffset = header.ElfHeaderSize; header.CreateIdent(Elf64IdentClass.Class64, Elf64IdentData.Data2LSB, null); // Calculate the concatenated size of all section's data uint offset = 0; foreach (Mosa.Runtime.Linker.Elf64.Sections.Elf64Section section in Sections) { offset += (uint)section.Length; } offset += (uint)nullSection.Length; offset += (uint)stringTableSection.Length; // Calculate offsets header.ProgramHeaderOffset = (uint)header.ElfHeaderSize + (uint)header.SectionHeaderEntrySize * (uint)header.SectionHeaderNumber + offset; header.SectionHeaderStringIndex = (ushort)((ushort)header.ProgramHeaderOffset + (ushort)header.ProgramHeaderNumber * (ushort)header.ProgramHeaderEntrySize); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); // Write the ELF Header header.Write(writer); // Overjump the Section Header Table and write the section's data first long tmp = fs.Position; writer.Seek((int)(tmp + header.SectionHeaderNumber * header.SectionHeaderEntrySize), System.IO.SeekOrigin.Begin); nullSection.Write(writer); stringTableSection.Write(writer); // Write the sections foreach (Mosa.Runtime.Linker.Elf64.Sections.Elf64Section section in Sections) { section.Write(writer); } // Jump back to the Section Header Table writer.Seek((int)tmp, System.IO.SeekOrigin.Begin); nullSection.WriteHeader(writer); stringTableSection.WriteHeader(writer); // Write the section headers foreach (Mosa.Runtime.Linker.Elf64.Sections.Elf64Section section in Sections) { section.WriteHeader(writer); } } }
static void TestRaw() { using (var vorbis = new NVorbis.VorbisReader(@"..\..\..\TestFiles\2test.ogg")) using (var outFile = System.IO.File.Create(@"..\..\..\TestFiles\2test.wav")) using (var writer = new System.IO.BinaryWriter(outFile)) { writer.Write(Encoding.ASCII.GetBytes("RIFF")); writer.Write(0); writer.Write(Encoding.ASCII.GetBytes("WAVE")); writer.Write(Encoding.ASCII.GetBytes("fmt ")); writer.Write(18); writer.Write((short)1); // PCM format writer.Write((short)vorbis.Channels); writer.Write(vorbis.SampleRate); writer.Write(vorbis.SampleRate * vorbis.Channels * 2); // avg bytes per second writer.Write((short)(2 * vorbis.Channels)); // block align writer.Write((short)16); // bits per sample writer.Write((short)0); // extra size writer.Write(Encoding.ASCII.GetBytes("data")); writer.Flush(); var dataPos = outFile.Position; writer.Write(0); var buf = new float[vorbis.SampleRate / 10 * vorbis.Channels]; int count; while ((count = vorbis.ReadSamples(buf, 0, buf.Length)) > 0) { for (int i = 0; i < count; i++) { var temp = (int)(32767f * buf[i]); if (temp > 32767) { temp = 32767; } else if (temp < -32768) { temp = -32768; } writer.Write((short)temp); } } writer.Flush(); writer.Seek(4, System.IO.SeekOrigin.Begin); writer.Write((int)(outFile.Length - 8L)); writer.Seek((int)dataPos, System.IO.SeekOrigin.Begin); writer.Write((int)(outFile.Length - dataPos - 4L)); writer.Flush(); } }
static int _m_Seek(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.BinaryWriter gen_to_be_invoked = (System.IO.BinaryWriter)translator.FastGetCSObj(L, 1); { int _offset = LuaAPI.xlua_tointeger(L, 2); System.IO.SeekOrigin _origin; translator.Get(L, 3, out _origin); var gen_ret = gen_to_be_invoked.Seek(_offset, _origin); LuaAPI.lua_pushint64(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
public static void Assemble(string infile, string outfile, string origin) { CurrentNdx = 0; AsLength = Convert.ToUInt16(origin, 16); IsEnd = false; ExecutionAddress = 0; LabelTable = new System.Collections.Hashtable(50); System.IO.BinaryWriter output; System.IO.TextReader input; System.IO.FileStream fs = new System.IO.FileStream(outfile, System.IO.FileMode.Create); output = new System.IO.BinaryWriter(fs); input = System.IO.File.OpenText(infile); SourceProgram = input.ReadToEnd(); input.Close(); output.Write('B'); output.Write('3'); output.Write('2'); output.Write(Convert.ToUInt16(origin, 16)); output.Write((ushort)0); Parse(output, origin); output.Seek(5, System.IO.SeekOrigin.Begin); output.Write(ExecutionAddress); output.Close(); fs.Close(); }
private void WriteTotal() { if (Valid) { Valid = false; bw.Seek(4, System.IO.SeekOrigin.Begin); bw.Write(BitConverter.GetBytes(m_totalsamplecount * 2 + 36), 0, 4); bw.Seek(32, System.IO.SeekOrigin.Current); bw.Write(BitConverter.GetBytes(m_totalsamplecount * 2), 0, 4); bw.Flush(); bw.Close(); if (AllDataWritten != null) { System.Diagnostics.Debug.WriteLine("Audio msg saved to file in thread " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); AllDataWritten.Invoke(this, null); } } }
private static void Main(string[] args) { int processID = GetProcessID(); if (processID != 0) { MemoryManager memoryManager = new MemoryManager(Process.GetProcessById(processID)); IntPtr startAddress = memoryManager.ImageBase + 0x1000; string pathToExecutable = GetPathToOriginalExecutable(); PeFile peFile = new PeFile(pathToExecutable); PeNet.Structures.IMAGE_SECTION_HEADER text_section = GetSectionHeader(peFile, ".text"); byte[] buffer = memoryManager.ReadBytes(startAddress, (int)text_section.VirtualSize); System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer)); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(new System.IO.MemoryStream(buffer)); System.IO.StreamWriter log = new System.IO.StreamWriter("log.txt"); foreach (var block in peFile.ImageRelocationDirectory) { foreach (var offset in block.TypeOffsets) { ulong rva = offset.Offset + block.VirtualAddress; log.WriteLine("relocation : 0x" + rva.ToString("X4")); log.Flush(); if (rva >= text_section.VirtualAddress && rva < text_section.VirtualAddress + text_section.VirtualSize) { switch (offset.Type) { case 3: int file_ofs = (int)(rva - text_section.VirtualAddress); reader.BaseStream.Seek(file_ofs, System.IO.SeekOrigin.Begin); ulong oldOffset = reader.ReadUInt64(); writer.Seek(file_ofs, System.IO.SeekOrigin.Begin); writer.Write((oldOffset - (ulong)memoryManager.ImageBase + peFile.ImageNtHeaders.OptionalHeader.ImageBase)); break; case 0: break; default: //throw new Exception("wrong relocation offset type"); break; } } } } int text_size = Math.Min(buffer.Length, (int)text_section.SizeOfRawData); System.IO.FileStream wow_file = System.IO.File.OpenRead(pathToExecutable); byte[] wow_data = new byte[wow_file.Length]; wow_file.Read(wow_data, 0, (int)wow_file.Length); writer = new System.IO.BinaryWriter(new System.IO.MemoryStream(wow_data)); writer.Seek((int)text_section.PointerToRawData, System.IO.SeekOrigin.Begin); writer.Write(buffer); System.IO.File.Open($"{pathToExecutable.TrimEnd('e').TrimEnd('x').Trim('e')}.dumped.exe", System.IO.FileMode.CreateNew).Write(wow_data, 0, wow_data.Length); } }
/// <summary>Signs a hash using the given private key.</summary> public static byte[] SignHash(byte[] data, byte[] priv) { ECDsaSigner signer = new ECDsaSigner(); ECPrivateKeyParameters curParams = new ECPrivateKeyParameters(new BigInteger(priv), _ecParams); signer.Init(true, curParams); // Generate the signature (produces the r and s values): BigInteger[] rs = signer.GenerateSignature(data); // Output stream: System.IO.MemoryStream stream = new System.IO.MemoryStream(); // Output writer: System.IO.BinaryWriter sig = new System.IO.BinaryWriter(stream); // Get r and s as bytes (signed arrays): byte[] rBa = rs[0].ToByteArray(); byte[] sBa = rs[1].ToByteArray(); // Sequence: sig.Write((byte)0x30); // Length (0 for now): sig.Write((byte)0); // Int: sig.Write((byte)(0x02)); sig.Write((byte)rBa.Length); sig.Write(rBa); // Int: sig.Write((byte)(0x02)); sig.Write((byte)sBa.Length); sig.Write(sBa); // Get the length: int length = (int)stream.Length; // Seek back and write the length - Goto 1: sig.Seek(1, System.IO.SeekOrigin.Begin); sig.Write((byte)length); // Get the data as a block of bytes: byte[] rawData = stream.ToArray(); stream.Close(); stream.Dispose(); return(rawData); }
/// <summary> /// Writes the specified fs. /// </summary> /// <param name="writer">The writer.</param> public void Write(System.IO.BinaryWriter writer) { writer.Seek(0, System.IO.SeekOrigin.Begin); writer.Write(Ident); writer.Write((ushort)Type); writer.Write((ushort)Machine); writer.Write((uint)Version); writer.Write(EntryAddress); writer.Write(ProgramHeaderOffset); writer.Write(SectionHeaderOffset); writer.Write(Flags); writer.Write(ElfHeaderSize); writer.Write(ProgramHeaderEntrySize); writer.Write(ProgramHeaderNumber); writer.Write(SectionHeaderEntrySize); writer.Write(SectionHeaderNumber); writer.Write(SectionHeaderStringIndex); }
public void MockFile_Copy_ShouldCloneContents() { var sourceFileName = XFS.Path(@"c:\source\demo.txt"); var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); var mockFileSystem = new MockFileSystem(); mockFileSystem.AddFile(sourceFileName, "Original"); mockFileSystem.File.Copy(sourceFileName, destFileName); using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) { var binaryWriter = new System.IO.BinaryWriter(stream); binaryWriter.Seek(0, SeekOrigin.Begin); binaryWriter.Write("Modified"); } Assert.AreEqual("Original", mockFileSystem.File.ReadAllText(destFileName)); }
int SystemIOBinaryWriter_m_Seek(RealStatePtr L, int gen_param_count) { ObjectTranslator translator = this; System.IO.BinaryWriter gen_to_be_invoked = (System.IO.BinaryWriter)translator.FastGetCSObj(L, 1); { int _offset = LuaAPI.xlua_tointeger(L, 2); System.IO.SeekOrigin _origin; translator.Get(L, 3, out _origin); long gen_ret = gen_to_be_invoked.Seek(_offset, _origin); LuaAPI.lua_pushint64(L, gen_ret); return(1); } }
public void MockFile_Copy_ShouldCloneBinaryContents() { var sourceFileName = XFS.Path(@"c:\source\demo.bin"); var destFileName = XFS.Path(@"c:\source\demo_copy.bin"); byte[] original = new byte[] { 0xC0 }; var mockFileSystem = new MockFileSystem(); mockFileSystem.AddFile(sourceFileName, new MockFileData(original)); mockFileSystem.File.Copy(sourceFileName, destFileName); using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) { var binaryWriter = new System.IO.BinaryWriter(stream); binaryWriter.Seek(0, SeekOrigin.Begin); binaryWriter.Write("Modified"); } CollectionAssert.AreEqual(original, mockFileSystem.File.ReadAllBytes(destFileName)); }
private void btnAssemble_Click(object sender, EventArgs e) { AsLength = Convert.ToUInt16(this.txtOrigin.Text, 16); System.IO.BinaryWriter output; System.IO.TextReader input; System.IO.FileStream fs = new System.IO.FileStream(this.txtOutputFileName.Text, System.IO.FileMode.Create); output = new System.IO.BinaryWriter(fs); input = System.IO.File.OpenText(this.txtSourceFileName.Text); SourceProgram = input.ReadToEnd(); input.Close(); output.Write('B'); output.Write('3'); output.Write('2'); output.Write(Convert.ToUInt16(this.txtOrigin.Text, 16)); output.Write((ushort)0); Parse(output); output.Seek(5, System.IO.SeekOrigin.Begin); output.Write(ExecutionAddress); output.Close(); fs.Close(); MessageBox.Show("Done!"); }
/// <summary> /// Save the Container to the Stream /// </summary> /// <param name="writer">the Stream Writer</param> internal void Save(System.IO.BinaryWriter writer, int offset) { writer.Write(offset); //prewrite Phase if (offset == -1) { version = VERSION; writer.Write(version); writer.Write((byte)type); writer.Write((int)items.Count); } else //Item writing Phase { writer.Seek(offset, System.IO.SeekOrigin.Begin); writer.Write(added.ToFileTime()); writer.Write(filename); for (int i = 0; i < items.Count; i++) { items[i].Save(writer); } } }
public void writetofile() { Byte[] checkBytes = System.IO.File.ReadAllBytes(filelocation); if (checkBytes[0x10] != 0x00 && checkBytes[0x10] != 0x01) { MessageBox.Show("Critical Error, file has not decrypted! aborting...", "Error", MessageBoxButtons.OK); return; } System.IO.BinaryWriter bw = new System.IO.BinaryWriter(System.IO.File.OpenWrite(filelocation)); if (gender != 0xff) { bw.Seek(0x284e0, System.IO.SeekOrigin.Begin); bw.Write((byte)gender); bw.Seek(0x284f4, System.IO.SeekOrigin.Begin); bw.Write((byte)0x01); } if (rainmakerrank != 0xff) { bw.Seek(0x2B238, System.IO.SeekOrigin.Begin); bw.Write((byte)rainmakerrank); } if (splatzonesrank != 0xff) { bw.Seek(0x2B244, System.IO.SeekOrigin.Begin); bw.Write((byte)splatzonesrank); } if (towercontrolrank != 0xff) { bw.Seek(0x2B250, System.IO.SeekOrigin.Begin); bw.Write((byte)towercontrolrank); } if (clamblitzrank != 0xff) { bw.Seek(0x2B25C, System.IO.SeekOrigin.Begin); bw.Write((byte)clamblitzrank); } bw.Dispose(); MessageBox.Show("Done!", "", MessageBoxButtons.OK); }
/// <summary> /// Creates the elf32 file. /// </summary> /// <param name="compiler">The compiler.</param> private void CreateElf64File(Mosa.Runtime.CompilerFramework.AssemblyCompiler compiler) { using (System.IO.FileStream fs = new System.IO.FileStream(this.OutputFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { Elf64Header header = new Elf64Header(); header.Type = Elf64FileType.Executable; header.Machine = Elf64MachineType.Intel386; header.SectionHeaderNumber = (ushort)(Sections.Count + 2); header.SectionHeaderOffset = header.ElfHeaderSize; header.CreateIdent(Elf64IdentClass.Class64, Elf64IdentData.Data2LSB, null); // Calculate the concatenated size of all section's data uint offset = 0; foreach (Mosa.Runtime.Linker.Elf64.Sections.Elf64Section section in Sections) { offset += (uint)section.Length; } offset += (uint)nullSection.Length; offset += (uint)stringTableSection.Length; // Calculate offsets header.ProgramHeaderOffset = (uint)header.ElfHeaderSize + (uint)header.SectionHeaderEntrySize * (uint)header.SectionHeaderNumber + offset; header.SectionHeaderStringIndex = (ushort)((ushort)header.ProgramHeaderOffset + (ushort)header.ProgramHeaderNumber * (ushort)header.ProgramHeaderEntrySize); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); // Write the ELF Header header.Write(writer); // Overjump the Section Header Table and write the section's data first long tmp = fs.Position; writer.Seek((int)(tmp + header.SectionHeaderNumber * header.SectionHeaderEntrySize), System.IO.SeekOrigin.Begin); nullSection.Write(writer); stringTableSection.Write(writer); // Write the sections foreach (Mosa.Runtime.Linker.Elf64.Sections.Elf64Section section in Sections) section.Write(writer); // Jump back to the Section Header Table writer.Seek((int)tmp, System.IO.SeekOrigin.Begin); nullSection.WriteHeader(writer); stringTableSection.WriteHeader(writer); // Write the section headers foreach (Mosa.Runtime.Linker.Elf64.Sections.Elf64Section section in Sections) section.WriteHeader(writer); } }
/// <summary> /// Creates the elf32 file. /// </summary> /// <param name="compiler">The compiler.</param> private void CreateElf32File(CompilerFramework.AssemblyCompiler compiler) { using (System.IO.FileStream fs = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { Elf32Header header = new Elf32Header(); header.Type = Elf32FileType.Executable; header.Machine = Elf32MachineType.Intel386; header.SectionHeaderNumber = (ushort)(Sections.Count + 2); header.SectionHeaderOffset = header.ElfHeaderSize; header.CreateIdent(Elf32IdentClass.Class32, Elf32IdentData.Data2LSB, null); // Calculate the concatenated size of all section's data uint offset = 0; foreach (Elf32Section section in Sections) { offset += (uint)section.Length; } offset += (uint)_nullSection.Length; offset += (uint)_stringTableSection.Length; // Calculate offsets header.ProgramHeaderOffset = header.ElfHeaderSize + header.SectionHeaderEntrySize * (uint)header.SectionHeaderNumber + offset; header.ProgramHeaderNumber = 1; header.SectionHeaderStringIndex = 1; System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); // Write the ELF Header header.Write(writer); // Overjump the Section Header Table and write the section's data first long tmp = fs.Position; writer.Seek((int)(tmp + header.SectionHeaderNumber * header.SectionHeaderEntrySize), System.IO.SeekOrigin.Begin); _nullSection.Write(writer); _stringTableSection.Write(writer); // Write the _sections foreach (Elf32Section section in Sections) section.Write(writer); // Jump back to the Section Header Table writer.Seek((int)tmp, System.IO.SeekOrigin.Begin); _nullSection.WriteHeader(writer); _stringTableSection.WriteHeader(writer); // Write the section headers foreach (Elf32Section section in Sections) section.WriteHeader(writer); Elf32ProgramHeader pheader = new Elf32ProgramHeader { Alignment = 0, FileSize = (uint)GetSection(SectionKind.Text).Length }; pheader.MemorySize = pheader.FileSize; pheader.VirtualAddress = 0xFF0000; pheader.Flags = Elf32ProgramHeaderFlags.Execute | Elf32ProgramHeaderFlags.Read | Elf32ProgramHeaderFlags.Write; pheader.Offset = ((Elf32Section)GetSection(SectionKind.Text)).Header.Offset; pheader.Type = Elf32ProgramHeaderType.Load; writer.Seek((int)header.ProgramHeaderOffset, System.IO.SeekOrigin.Begin); pheader.Write(writer); } }
/// <summary> /// Creates the elf32 file. /// </summary> /// <param name="compiler">The compiler.</param> private void CreateElf32File(CompilerFramework.AssemblyCompiler compiler) { using (System.IO.FileStream fs = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { Elf32Header header = new Elf32Header(); header.Type = Elf32FileType.Executable; header.Machine = Elf32MachineType.Intel386; header.SectionHeaderNumber = (ushort)(Sections.Count + 2); header.SectionHeaderOffset = header.ElfHeaderSize; header.CreateIdent(Elf32IdentClass.Class32, Elf32IdentData.Data2LSB, null); // Calculate the concatenated size of all section's data uint offset = 0; foreach (Elf32Section section in Sections) { offset += (uint)section.Length; } offset += (uint)_nullSection.Length; offset += (uint)_stringTableSection.Length; // Calculate offsets header.ProgramHeaderOffset = header.ElfHeaderSize + header.SectionHeaderEntrySize * (uint)header.SectionHeaderNumber + offset; header.ProgramHeaderNumber = 1; header.SectionHeaderStringIndex = 1; System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); // Write the ELF Header header.Write(writer); // Overjump the Section Header Table and write the section's data first long tmp = fs.Position; writer.Seek((int)(tmp + header.SectionHeaderNumber * header.SectionHeaderEntrySize), System.IO.SeekOrigin.Begin); _nullSection.Write(writer); _stringTableSection.Write(writer); // Write the _sections foreach (Elf32Section section in Sections) { section.Write(writer); } // Jump back to the Section Header Table writer.Seek((int)tmp, System.IO.SeekOrigin.Begin); _nullSection.WriteHeader(writer); _stringTableSection.WriteHeader(writer); // Write the section headers foreach (Elf32Section section in Sections) { section.WriteHeader(writer); } Elf32ProgramHeader pheader = new Elf32ProgramHeader { Alignment = 0, FileSize = (uint)GetSection(SectionKind.Text).Length }; pheader.MemorySize = pheader.FileSize; pheader.VirtualAddress = 0xFF0000; pheader.Flags = Elf32ProgramHeaderFlags.Execute | Elf32ProgramHeaderFlags.Read | Elf32ProgramHeaderFlags.Write; pheader.Offset = ((Elf32Section)GetSection(SectionKind.Text)).Header.Offset; pheader.Type = Elf32ProgramHeaderType.Load; writer.Seek((int)header.ProgramHeaderOffset, System.IO.SeekOrigin.Begin); pheader.Write(writer); } }
private void button1_Click_1(object sender, EventArgs e) { int colour; int i; output = new Byte[bmp.Height, bmp.Width]; for (int row = 0; row < bmp.Height; row++) { Color[] rowColors = new Color[MaxColoursPerRow]; int colorCount = 0; for (int stitch = 0; stitch < bmp.Width; stitch++) { thisStitch = bmp.GetPixel(stitch, row); if (!rowColors.Contains(thisStitch)) { rowColors[colorCount++] = thisStitch; } } for (int stitch = 0; stitch < bmp.Width; stitch++) { thisStitch = bmp.GetPixel(stitch, row); for (i = 0; i < colors.Length; i++) { if (thisStitch == colors[i]) { colour = Convert.ToInt32(colorNumber[i].Text); output[row, stitch] = (Byte)colour; break; } } } } // Array 'output' now contains one byte per pixel (stitch), with number representing colour of yarn to use. Let's dump it to a file for reference. System.IO.StreamWriter stream = new System.IO.StreamWriter("C:\\Knitulator\\proof.txt"); for (int row = 0; row < bmp.Height; row++) { for (int stitch = 0; stitch < bmp.Width; stitch++) { stream.Write(output[row, stitch].ToString()); } stream.WriteLine(); } stream.Close(); // Now lets create a 2 colour pattern, where each row contains a boolean indicating do or don't use the contrast yarn. int widthInBits = (int)(8 * Math.Round(bmp.Width / (double)8, MidpointRounding.AwayFromZero)); // must be multiple of 8 bits Byte[,] pattern = new Byte[bmp.Height, widthInBits]; // Array to hold pattern data = 1 byte represents 8 stitches System.IO.StreamWriter stream2 = new System.IO.StreamWriter("C:\\Knitulator\\2col.txt"); int n = bmp.Height; stream2.WriteLine("Row : Row Pattern"); for (int row = 0; row < bmp.Height; row++) { stream2.Write((bmp.Height - row).ToString("D3") + " : "); n--; for (int stitch = 0; stitch < bmp.Width; stitch++) { if (output[row, stitch] == 2) { stream2.Write("X"); pattern[row, stitch] = 1; } else { stream2.Write("."); pattern[row, stitch] = 0; } } stream2.WriteLine(); } stream2.Close(); // Now create binary array in brother format, 1 bit per pixel Byte[,] patternOut = new Byte[bmp.Height, widthInBits / 8]; for (int row = 0; row < bmp.Height; row++) { Byte bit = 0; for (int stitch = 0; stitch < widthInBits; stitch++) { bit = (Byte)(stitch & 0x07); bit = (Byte)(0x80 >> bit); patternOut[row, stitch / 8] = (Byte)(patternOut[row, stitch / 8] | ((2 ^ bit) * pattern[row, stitch])); } } System.IO.FileStream fs = new System.IO.FileStream("C:\\Knitulator\\track-01.dat", System.IO.FileMode.OpenOrCreate); System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(fs); binaryWriter.Seek(0, System.IO.SeekOrigin.Begin); binaryWriter.Write((Byte)0x01); binaryWriter.Write((Byte)0x20); Byte heightHundreds = (Byte)((bmp.Height) / 100); Byte heightTens = (Byte)(((bmp.Height) / 10) - (10 * heightHundreds)); Byte heightUnits = (Byte)((bmp.Height) - (10 * heightTens) - (100 * heightHundreds)); Byte widthHundreds = (Byte)((widthInBits) / 100); Byte widthTens = (Byte)(((widthInBits) / 10) - (10 * widthHundreds)); Byte widthUnits = (Byte)((widthInBits) - (10 * widthTens) - (100 * widthHundreds)); binaryWriter.Write((Byte)((heightHundreds << 4) + heightTens)); binaryWriter.Write((Byte)((heightUnits << 4) + widthHundreds)); binaryWriter.Write((Byte)((widthTens << 4) + widthUnits)); binaryWriter.Write((Byte)0x49);// 49 binaryWriter.Write((Byte)0x01);//01 = pattern mode 8 number 901 binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x09); binaryWriter.Write((Byte)0x02); binaryWriter.Seek(0x7ee0 - (bmp.Height * widthInBits / 8), System.IO.SeekOrigin.Begin); for (int row = 0; row < bmp.Height ; row++) { for (int stitchBlock = 0; stitchBlock < widthInBits / 8; stitchBlock++) { binaryWriter.Write(patternOut[row, stitchBlock]); Console.Write(patternOut[row, stitchBlock].ToString("X2") + " "); } Console.WriteLine(); } binaryWriter.Close(); fs.Close(); MessageBox.Show("Conversion Complete."); }
private void button2_Click(object sender, EventArgs e) { int colour; int i; output = new Byte[bmp.Height, bmp.Width]; for (int row = 0; row < bmp.Height; row++) { Color[] rowColors = new Color[MaxColoursPerRow]; int colorCount = 0; for (int stitch = 0; stitch < bmp.Width; stitch++) { thisStitch = bmp.GetPixel(stitch, row); if (!rowColors.Contains(thisStitch)) { rowColors[colorCount++] = thisStitch; } } for (int stitch = 0; stitch < bmp.Width; stitch++) { thisStitch = bmp.GetPixel(stitch, row); for (i = 0; i < colors.Length; i++) { if (thisStitch == colors[i]) { colour = Convert.ToInt32(colorNumber[i].Text); output[row, stitch] = (Byte)colour; break; } } } } // Array 'output' now contains one byte per pixel (stitch), with number representing colour of yarn to use. Let's dump it to a file for reference. System.IO.StreamWriter stream = new System.IO.StreamWriter("C:\\Knitulator\\Frontproof.txt"); for (int row = 0; row < bmp.Height; row++) { for (int stitch = 0; stitch < bmp.Width; stitch++) { stream.Write(output[row, stitch].ToString()); } stream.WriteLine(); } stream.Close(); // Now lets create a Multicolour pattern, where each row contains a boolean indicating do or don't use the colour. // A separate array is required, for each row to indicate which colour to use. //TOD: Make sure patternRowColour is multiple of 2 as colours are stored as nibbles Byte[] patternRowColour = new Byte[bmp.Height * MaxColoursPerRow]; // Array to hold colour of yarn to use on each Multicolour row int widthInBits = (int)(8 * Math.Round(bmp.Width / (double)8, MidpointRounding.AwayFromZero)); // must be multiple of 8 bits Byte[,] pattern = new Byte[bmp.Height * MaxColoursPerRow, widthInBits]; // Array to hold pattern data = 1 byte represents 8 stitches System.IO.StreamWriter stream2 = new System.IO.StreamWriter("C:\\Knitulator\\Frontmc.txt"); int n = bmp.Height * MaxColoursPerRow; stream2.WriteLine("Row : Disp : Col : Row Pattern"); for (int row = 0; row < bmp.Height; row++) { // Work out which colours to knit: Byte[] rowColours = new Byte[MaxColoursPerRow]; int colourCount = 0; for (int stitch = 0; stitch < bmp.Width; stitch++) { if (!rowColours.Contains(output[row, stitch])) { rowColours[colourCount++] = output[row, stitch]; } } if (rowColours[1] == 0) { rowColours[1] = 8; rowColours[2] = 9; } if (rowColours[2] == 0) { rowColours[2] = 9; } for (i = 0; i < MaxColoursPerRow; i++) { stream2.Write((bmp.Height - row).ToString("D3") + " : "); stream2.Write(n.ToString("D3") + " : "); n--; stream2.Write(rowColours[i].ToString() + " : "); patternRowColour[row * MaxColoursPerRow + i] = rowColours[i]; for (int stitch = 0; stitch < bmp.Width; stitch++) { if (output[row, stitch] == rowColours[i]) { stream2.Write("X"); pattern[MaxColoursPerRow * row + i, stitch] = 1; } else { stream2.Write("."); pattern[MaxColoursPerRow * row + i, stitch] = 0; } } stream2.WriteLine(); } } stream2.Close(); // Now create binary array in brother format, 1 bit per pixel Byte[,] patternOut = new Byte[bmp.Height * MaxColoursPerRow, widthInBits / 8]; for (int row = 0; row < bmp.Height * MaxColoursPerRow; row++) { Byte bit = 0; for (int stitch = 0; stitch < widthInBits; stitch++) { bit = (Byte)(stitch & 0x07); bit = (Byte)(0x80 >> bit); if (pattern[row, stitch] != 0) { patternOut[row, stitch / 8] = (Byte)(patternOut[row, stitch / 8] | ( bit) ); } // patternOut[row, stitch / 8] = (Byte)(patternOut[row, stitch / 8] | ((pattern[row, stitch] == 0) ? 0 : (2 ^ bit) )); } } System.IO.FileStream fs = new System.IO.FileStream("C:\\Knitulator\\track-01.dat", System.IO.FileMode.OpenOrCreate); System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(fs); binaryWriter.Seek(0, System.IO.SeekOrigin.Begin); binaryWriter.Write((Byte)0x01); binaryWriter.Write((Byte)0x20); Byte heightHundreds = (Byte)((bmp.Height * MaxColoursPerRow) / 100); Byte heightTens = (Byte)(((bmp.Height * MaxColoursPerRow) / 10) - (10 * heightHundreds)); Byte heightUnits = (Byte)((bmp.Height * MaxColoursPerRow) - (10 * heightTens) - (100 * heightHundreds)); Byte widthHundreds = (Byte)((widthInBits) / 100); Byte widthTens = (Byte)(((widthInBits) / 10) - (10 * widthHundreds)); Byte widthUnits = (Byte)((widthInBits) - (10 * widthTens) - (100 * widthHundreds)); //binaryWriter.Write((Byte)0x77);//774 high //binaryWriter.Write((Byte)0x41); //binaryWriter.Write((Byte)0x74);// 174 wide binaryWriter.Write((Byte)((heightHundreds << 4) + heightTens)); binaryWriter.Write((Byte)((heightUnits << 4) + widthHundreds)); binaryWriter.Write((Byte)((widthTens << 4) + widthUnits)); binaryWriter.Write((Byte)0x89);// 89 binaryWriter.Write((Byte)0x01);//01 = pattern mode 8 number 901 binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x00); binaryWriter.Write((Byte)0x09); binaryWriter.Write((Byte)0x02); //fs.Position = 0x7ee0 - (patternRowColour.Length / 2) - (bmp.Height * MaxColoursPerRow * widthInBits / 8); //binaryWriter = new System.IO.BinaryWriter(fs); binaryWriter.Seek(0x7ee0 - (patternRowColour.Length / 2) - (bmp.Height * MaxColoursPerRow * widthInBits / 8), System.IO.SeekOrigin.Begin); for (int row = 0; row < bmp.Height * MaxColoursPerRow; row++) { for (int stitchBlock = 0; stitchBlock < widthInBits / 8; stitchBlock++) { binaryWriter.Write(patternOut[row, stitchBlock]); Console.Write(patternOut[row, stitchBlock].ToString("X2") + " "); } Console.WriteLine(); } //binaryWriter.Close(); //fs.Close(); //System.IO.FileStream fs2 = new System.IO.FileStream("C:\\Users\\kevin.blain\\Documents\\track-01.dat", System.IO.FileMode.OpenOrCreate); //fs2.Position = 0x7ee0 - (patternRowColour.Length/2); binaryWriter = new System.IO.BinaryWriter(fs); for (int row = 0; row < bmp.Height * MaxColoursPerRow; row += 2) { Byte colourInfo = 0; if (patternRowColour[row] == 0) { colourInfo = 1 << 4; } else { colourInfo = (Byte)(patternRowColour[row] << 4); } if (patternRowColour[row + 1] == 0) { colourInfo += 1; } else { colourInfo += (Byte)(patternRowColour[row + 1]); } binaryWriter.Write(colourInfo); } binaryWriter.Close(); fs.Close(); MessageBox.Show("Conversion Complete."); }
public static bool SetBoolValue(string ValueName, bool ValueToSet, string ConfigFileName) { try { var SettingsPath = UnityEngine.Application.dataPath.Remove(UnityEngine.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. var 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) { return(false); } tempStr = GetStringFromBinaryReader(br); // "Base" if (tempStr != "Base") { 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) { var SettingType = GetStringFromBinaryReader(br); var SettingName = GetStringFromBinaryReader(br); if (SettingName == ValueName) { break; } br.BaseStream.Seek(24, System.IO.SeekOrigin.Current); if (GetSizeofTypeByString(SettingType) == -1) { return(false); } SettingsOffset += GetSizeofTypeByString(SettingType); } // Set the setting in the file var 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 (System.Exception) { // Error happened return(false); } // Success! return(true); }