using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace poc_binary { class Unit { /// /// Name is the name of the unit this instance represents. /// public string Name = ""; /// /// The name of the faction this Unit belongs to /// public string Faction = ""; /// /// Dynamic array for this Unit instances' unit options /// public List Options = new List(); /// /// Dynamic array for this Unit instances' something eles /// public List SomeOptions = new List(); public Unit(string sPath) { try { FileStream fs = File.Open(sPath, FileMode.Open); BinaryReader br = new BinaryReader(fs); // Read string reads a 7 bit encoded int which represents the length of the following string // and then reads that many characters. this.Name = br.ReadString(); this.Faction = br.ReadString(); // When saving this we wrote a 32 bit (int) to file, which represented the amount of entries in the dynamic array (list) int iCount = br.ReadInt32(); // We now read iCount strings from the file for (int i = 0; i < iCount; i++) { this.Options.Add(br.ReadString()); } // Do the same for SomeOptions (placeholder) iCount = br.ReadInt32(); // We now read iCount strings from the file for (int i = 0; i < iCount; i++) { this.SomeOptions.Add(br.ReadString()); } // Cleanup br.Close(); fs.Close(); } catch (IOException e) { // Replace with whatever output stream you want to use, for example message boxes. Console.WriteLine("An error occured whilst trying to read " + sPath + " : " + e); } } /// /// Saves the unit's information to disk. /// public void Save(string sPath) { try { FileStream fs = File.Open(sPath, FileMode.OpenOrCreate); BinaryWriter bw = new BinaryWriter(fs); // Write the name and faction bw.Write(this.Name); bw.Write(this.Faction); // Write the amount of entries in Options bw.Write(this.Options.Count); // Write each string in options for (int i = 0; i < this.Options.Count; i++) { bw.Write(this.Options[i]); } // Do the same for SomeOptions bw.Write(this.SomeOptions.Count); for (int i = 0; i < this.SomeOptions.Count; i++) { bw.Write(this.SomeOptions[i]); } } catch (IOException e) { // Replace with whatever output stream you want to use, for example message boxes. Console.WriteLine("An error occured whilst trying to write " + sPath + " : " + e); } } } }