Exemplo n.º 1
0
        private void LoadInventory()
        {
            // Decided to switch to just using JSON to store the inventory
            try
            {
                using (Stream stream = File.OpenRead(DBLoc))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Inventory));
                    Inv = (Inventory)serializer.ReadObject(stream);
                    Inv.CorrectItemErrors();                     // No idea why I need this
                }
            }
            catch
            {
                // using statements automatically close IDisposible objects
                using (StreamReader sr = new StreamReader(DBLoc))
                {
                    string head = sr.ReadLine();

                    string headId = head.Split(',')[0];
                    headId = headId.Remove(0, 2);
                    int itemcount = int.Parse(headId);
                    Inv = new Inventory();

                    for (int i = 0; i < itemcount; i++)
                    {
                        string currentitem = sr.ReadLine();

                        // Created this CSVHelper in case some idiot decides to put a
                        // comma in a name or something and corrupt the inventory file.
                        Item item = CSVHelper.DeserializeItem(currentitem);
                        Inv.Items.Add(item.Id, item);
                    }
                }
                int    j        = 0;
                string filename = Path.Combine(Path.GetDirectoryName(DBLoc), Path.GetFileNameWithoutExtension(DBLoc)
                                               + ".old" + Path.GetExtension(DBLoc));

                while (File.Exists(filename))
                {
                    filename = Path.Combine(Path.GetDirectoryName(DBLoc), Path.GetFileNameWithoutExtension(DBLoc)
                                            + ".old" + j++.ToString() + Path.GetExtension(DBLoc));
                }

                File.Move(DBLoc, filename);
                DBLoc = Path.Combine(Path.GetDirectoryName(DBLoc), Path.GetFileNameWithoutExtension(DBLoc) + ".json");
                SaveInventory();
            }
        }
Exemplo n.º 2
0
 public override string ToString()
 {
     return(CSVHelper.SerializeItem(this));
 }