![](/img/trans.png)
[英]I didn't see any data on data grid view. Localdb didn't send any data (northwind)
[英]Why is data in JSON file didn't change, but in runtime I can see new data
我在项目中有一个 JSON 文件,我想更改其中的一些数据。 我编写了代码,它在运行时更改了数据,但项目中的 JSON 文件没有任何更改。 请帮我找出问题所在。
这是 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);
}
}
}
这是 o model 用于 JSON 数据
namespace WorkWithJson.Model
{
public class PersonModel
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
}
}
这是我想要更改的 JSON
[
{
"name": "Pavel",
"surname": "Pypkin",
"age": 30
},
{
"name": "Fedot",
"surname": "Ikot",
"age": 900
}
]
这是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>
这是运行时的 output,但 TestData.json 文件保持不变
您可能面临两种情况。
Directory.GetCurrentDirectory()
可能不是bin
目录。 您可以打印完整路径并找出您实际正在编写的文件。Console.WriteLine(fileLocation);
File.WriteAllText
时一定有一些例外。 如果没有抛出异常,则不是这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.