Home > Mobile >  How to get character info from a file?
How to get character info from a file?

Time:04-18

I created a file which named by a given name by user, and add some stats in it for example : healt, power, speed, inventory like so. Now, i want to create a function that get stats from given path. It need find the file from given name and get the stat.

I tried re-read the file as note/json so on and it didnt work very well. I want to get variables like : if(inventory.Contains("Bread"))

Note : I tried to save files as .json but it saved as unknown note i dont know how and why.

        ...
        ...
        CharacterData Character = new CharacterData()
        {
            health = 100,
            power = 100,
            speed = 100,
            dexterity = 100,
            hungry = 100,
            weapon = "Fist",
            inventory = new List<string>()
            {
                "Bread"
            }
        };
        string stringjson = JsonConvert.SerializeObject(Character);
        File.WriteAllText(characterPath, stringjson);
    }
    public int GetCharInfo(string charName,string stat)
    {
        //return (stat value)

    }

CodePudding user response:

I guess begin with File.ReadAllText(path) Example of usage and documentation

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readalltext?view=net-6.0

Then you can covert the result to JSON and extract the information that you want

CodePudding user response:

you can do something like this:

CharacterData Character = new CharacterData()
{
    health = 100,
    power = 100,
    speed = 100,
    dexterity = 100,
    hungry = 100,
    weapon = "Fist",
    inventory = new List<string>()
    {
        "Bread"
    }
};


string stringjson = JsonConvert.SerializeObject(Character);

string path = @"C:\DEV\StackOverflow\";
string characterPath = path   "johnny.json";

File.WriteAllText(characterPath, stringjson);

public int GetCharInfo(string charName, string stat)
{
    string json = File.ReadAllText(path   $"{charName}.json");
    JObject obj = JObject.Parse(json);
    return (int)obj[stat];
}

now if you call:

GetCharInfo("johnny", "power")

you will get the value:

100

also, if you want to see if the key exists you can use the ContainsKey method on JObject like such:

if(obj.ContainsKey(stat))
        return (int)obj[stat];
  • Related