Home > Net >  Why is data in JSON file didn't change, but in runtime I can see new data
Why is data in JSON file didn't change, but in runtime I can see new data

Time:09-02

I have a JSON file in the project and I want to change some data in it. I wrote code it changed data in runtime but the JSON file in the project stayed without any changes. Please help me find the problem.

This is code in Programm.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.IO;
using WorkWithJson.Model;

namespace WorkWithJson
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var fileLocation = Path.Combine(Directory.GetCurrentDirectory(), "Data", "TestData.json");

            var oldData = File.ReadAllText(fileLocation);           

            var jsonSettings = new JsonSerializerSettings();
            jsonSettings.Converters.Add(new ExpandoObjectConverter());
            jsonSettings.Converters.Add(new StringEnumConverter());

            dynamic newData = JsonConvert.DeserializeObject<List<PersonModel>>(oldData, jsonSettings);

            newData[0].Name = "Pipiter";

            var newJson = JsonConvert.SerializeObject(newData, Formatting.Indented, jsonSettings);

            File.WriteAllText(fileLocation, newJson);
        }
    }
}

This is o model for JSON data

namespace WorkWithJson.Model
{
    public class PersonModel
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}

And this is JSON which I want change

[
  {
    "name": "Pavel",
    "surname": "Pypkin",
    "age": 30
  },
  {
    "name": "Fedot",
    "surname": "Ikot",
    "age": 900
  }
]


This is csproj.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
    <PackageReference Include="System.Text.Json" Version="6.0.5" />
  </ItemGroup>

  <ItemGroup>
    <None Update="Data\TestData.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

This is output in runtime, but the TestData.json file stayed without any changes

Runtime output

CodePudding user response:

There may be 2 conditions you are facing.

  1. You are running this program in IDE, the Directory.GetCurrentDirectory() maybe not the bin dir. You can print the full path and findout which file you are actually writing.
Console.WriteLine(fileLocation);
  1. You may have some software openning the json file which has been locked. It must be some exception when File.WriteAllText. If no exception thrown, not this issue.
  • Related