Home > Enterprise >  WPF: Save and read Json file in Documents folder
WPF: Save and read Json file in Documents folder

Time:09-16

I'm making a simple WPF program:

How do I save json string in a data.json file in Documents folder and read them back using Json.NET?

My Code:

    public void SerializeTest()
    {
        for (int i = 0; i < 3; i  )
        {
            Product product = new Product();
            product.Name = "Item "   i;

            productList.Add(product);
        }

        json = JsonConvert.SerializeObject(productList, Formatting.Indented);
    }

CodePudding user response:

I guess what you are looking for is

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

You can use this and append to get to your desired file.

json = JsonConvert.SerializeObject(productList, Formatting.Indented);
 
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)   "\\ExampleFolder\\ExampleSubFolder\\data.json";
        try
        {
                File.WriteAllText(path, json);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
  • Related