none
save/load progress in program RRS feed

  • Question

  • Good morning all. I am trying to find a way to save/load my values in this code but had no luck. making a simple text file  on c:\ directory would be fine to store the information. Appreciate the help!
    namespace ConsoleApp1
    {
        public class Car
        {
    
            public static void Main(String[] args)
    
            {
                
                Console.WriteLine("\nYou are in armory. (for a list of commands, type list)");
                int wallet = 0;
                
                while (true)
                {
                    
                    Console.WriteLine("\nEnter command:");
                    string answer = Console.ReadLine();
    
    
                    if (answer.Contains("list"))
                    {
                        Console.WriteLine("\ndig: go dig for gold");
                        Console.WriteLine("wallet: to check your gold");
                        Console.WriteLine("save: saves progress");
                        Console.WriteLine("load: loads progress"); 
                    }
                    else if (answer.Contains("dig"))
                    {
                        Console.WriteLine("You find 10 gold coins.");
                        wallet = wallet + 10;
                    }
                    else if (answer.Contains("wallet"))
                    {
                        Console.WriteLine("You have " + wallet + " gold coins.");
                    }
                    else if (answer.Contains("save"))
                    {
                        Console.WriteLine("saving progress");
                        // ???
                    }
                    else if (answer.Contains("load"))
                    {
                        Console.WriteLine("loading progress");
                        // ???
                    }
                    else
                    {
                        Console.WriteLine("Invalid Entry");
                    }
    
                }
                
            }
        }
    }
    

    Sunday, January 7, 2018 4:28 PM

Answers

  • Here is a very rudimentary example of how to use a text file in your code.
    It has minimal error checking, so it needs to be made more robust.

    Also note that writing a file to the root directory of the system drive
    may be restricted if you aren't running the program with admin rights.
    In that case the file will probably be written to a subdir of AppData
    for the current user if run from the IDE, or you will get an exception
    at run time if running from the command line.

    It is far better to store the file in a directory that you can access
    without admin rights.

    static void Main(string[] args)
    {
    
        Console.WriteLine("\nYou are in armory. (for a list of commands, type list)");
        int wallet = 0;
        string settings = @"C:\settings.txt";
    
        while (true)
        {
    
            Console.WriteLine("\nEnter command:");
            string answer = Console.ReadLine();
    
    
            if (answer.Contains("list"))
            {
                Console.WriteLine("\ndig: go dig for gold");
                Console.WriteLine("wallet: to check your gold");
                Console.WriteLine("save: saves progress");
                Console.WriteLine("load: loads progress");
            }
            else if (answer.Contains("dig"))
            {
                Console.WriteLine("You find 10 gold coins.");
                wallet = wallet + 10;
            }
            else if (answer.Contains("wallet"))
            {
                Console.WriteLine("You have " + wallet + " gold coins.");
            }
            else if (answer.Contains("save"))
            {
                Console.WriteLine("saving progress");
                // ???
                using (System.IO.StreamWriter file =
                    new System.IO.StreamWriter(settings))
                {
                    file.WriteLine(wallet.ToString());
                }
            }
            else if (answer.Contains("load"))
            {
                Console.WriteLine("loading progress");
                // ???
                if (System.IO.File.Exists(settings))
                {
                    using (System.IO.StreamReader file =
                        new System.IO.StreamReader(settings))
                    {
                        string str = file.ReadLine();
                        if (!int.TryParse(str, out wallet))
                        {
                            Console.WriteLine("Ooops! File contents not an integer!");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No file to load!");
                }
    
            }
            else
            {
                Console.WriteLine("Invalid Entry");
            }
        }
    }
    

    - Wayne

    • Marked as answer by J3KB0T Sunday, January 7, 2018 7:30 PM
    Sunday, January 7, 2018 6:14 PM

All replies

  • Here is one option, it shows the basics to writing and reading to a binary file. Please read the comments within to expand upon what is shown as this is nothing more than a working code sample to show how to read and write to a binary file as you will need to expand upon this. The key is the classes and marking them as serializable.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace ConsoleApp1
    {
        class Program
        {
            /// <summary>
            /// In a real app you would check to see if the dat file
            /// exists, if so load it rather than write information to
            /// the file which I will leave to the developer.
            /// 
            /// Read about Collectionbase (see link below) to see
            /// what is possible. Using what is shown in combination
            /// with lambda and/or linq or conventional for/next you
            /// can find, update along with remove items. If information
            /// needs to be sorted, that can be done after loading the
            /// data.
            /// 
            /// There is a indexer/primary key, when adding you could
            /// use lambda or linq or a for/next to find the last indexer
            /// used and increment it for a new player.
            /// </summary>
            /// <param name="args"></param>
            static void Main(string[] args)
            {
                Players players = new Players();
    
                players.Add(new Player(1, "Payne"));
                players.Add(new Player(2, "Adams"));
                players.Add(new Player(3, "Gallagher"));
    
                string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Players.dat");
    
                Serialize(players, fileName);
                Deserialize(fileName);
    
                Console.ReadLine();
    
            }
            public static void Serialize(Players pPlayers, string pFilename)
            {
                var ms = File.OpenWrite(pFilename);
                var formatter = new BinaryFormatter();
    
                formatter.Serialize(ms, pPlayers);
    
                ms.Flush();
                ms.Close();
                ms.Dispose();
    
            }
            public static void Deserialize(String pFilename)
            {
                var formatter = new BinaryFormatter();
                var fs = File.Open(pFilename, FileMode.Open);
                var players = formatter.Deserialize(fs);
                Players pobject = (Players)players;
    
                fs.Flush();
                fs.Close();
                fs.Dispose();
    
                foreach (Player player in pobject)
                {
                    Console.WriteLine($"{player.Identifier}, {player.Name}");
                }
            }
        }
    
        [Serializable]
        public class Player
        {
            public Player(int pIdentifier, string pName)
            {
                Identifier = pIdentifier;
                Name = pName;
            }
    
            public int Identifier { get; set; }
            public string Name { get; set; }
    
        }
        /// <summary>
        /// See https://msdn.microsoft.com/en-us/library/system.collections.collectionbase%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
        /// for Collectionbase
        /// 
        /// You can add to this e.g. remove for instance, using lambda or LINQ
        /// find a player, update the player and save back via the serilization
        /// method.
        /// </summary>
        [Serializable]
        public class Players : CollectionBase
        {
            public void Add(Player pPlayer)
            {
                List.Add(pPlayer);
            }
            public Player this[int pIndex]
            {
                get
                {
                    return (Player)List[pIndex];
                }
                set
                {
                    List.Add(value);
                }
            }
        }
    }
    

    Other options are working from a xml file or comma-delimited file for instance.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites



    Sunday, January 7, 2018 5:26 PM
    Moderator
  • I am trying to find a way to save/load my values in this code but had no luck. making a simple text file  on c:\ directory would be fine to store the information.

    You have to decide whether you want to have the file in text mode - so it
    can be easily read (for example in Notepad), or in binary format.

    For a text file see:

    How to: Write to a Text File (C# Programming Guide)
    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

    How to: Read From a Text File (C# Programming Guide)
    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file

    - Wayne

    Sunday, January 7, 2018 5:29 PM
  • Here is a very rudimentary example of how to use a text file in your code.
    It has minimal error checking, so it needs to be made more robust.

    Also note that writing a file to the root directory of the system drive
    may be restricted if you aren't running the program with admin rights.
    In that case the file will probably be written to a subdir of AppData
    for the current user if run from the IDE, or you will get an exception
    at run time if running from the command line.

    It is far better to store the file in a directory that you can access
    without admin rights.

    static void Main(string[] args)
    {
    
        Console.WriteLine("\nYou are in armory. (for a list of commands, type list)");
        int wallet = 0;
        string settings = @"C:\settings.txt";
    
        while (true)
        {
    
            Console.WriteLine("\nEnter command:");
            string answer = Console.ReadLine();
    
    
            if (answer.Contains("list"))
            {
                Console.WriteLine("\ndig: go dig for gold");
                Console.WriteLine("wallet: to check your gold");
                Console.WriteLine("save: saves progress");
                Console.WriteLine("load: loads progress");
            }
            else if (answer.Contains("dig"))
            {
                Console.WriteLine("You find 10 gold coins.");
                wallet = wallet + 10;
            }
            else if (answer.Contains("wallet"))
            {
                Console.WriteLine("You have " + wallet + " gold coins.");
            }
            else if (answer.Contains("save"))
            {
                Console.WriteLine("saving progress");
                // ???
                using (System.IO.StreamWriter file =
                    new System.IO.StreamWriter(settings))
                {
                    file.WriteLine(wallet.ToString());
                }
            }
            else if (answer.Contains("load"))
            {
                Console.WriteLine("loading progress");
                // ???
                if (System.IO.File.Exists(settings))
                {
                    using (System.IO.StreamReader file =
                        new System.IO.StreamReader(settings))
                    {
                        string str = file.ReadLine();
                        if (!int.TryParse(str, out wallet))
                        {
                            Console.WriteLine("Ooops! File contents not an integer!");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No file to load!");
                }
    
            }
            else
            {
                Console.WriteLine("Invalid Entry");
            }
        }
    }
    

    - Wayne

    • Marked as answer by J3KB0T Sunday, January 7, 2018 7:30 PM
    Sunday, January 7, 2018 6:14 PM