Reputation: 455
Current JSON file looks like this
[
{
"name": "company xyz",
"path": "C:\\xxx\\xyz"
},
{
"name": "company abc",
"path": "C:\\xxx\\abc"
}
]
Client Class
public string Name { get; set; }
public string Path { get; set; }
I use the below to pull from the file and display in a combo, this works fine
public static List<Client> GetList()
{
// Retrieve JSON data from file
var json = File.ReadAllText(fileName);
return JsonConvert.DeserializeObject<List<Client>>(json);
}
I would now like to be able to Search for a specific node and Update that content. I have the below code so far which does find the node based on the search string I pass but I'm at a loss at how to now Save the updated node (found) back into the JSON file whilst removing the previous?
public static void Update(Client c, string s)
{
var json = File.ReadAllText(fileName);
List<Client> list = JsonConvert.DeserializeObject<List<Client>>(json);
Client found = list.Where(x => x.Name == s).Single();
found.Name = c.Name;
found.Path = c.Path;
}
Upvotes: 1
Views: 810
Reputation: 879
Try this:
public static void Update(Client c, string s)
{
var json = File.ReadAllText(fileName);
List<Client> list = JsonConvert.DeserializeObject<List<Client>>(json);
Client found = list.Where(x => x.Name == s).Single();
found.Name = c.Name;
found.Path = c.Path;
var updatedJson = JsonConvert.SerializeObject(list);
File.WriteAllText(fileName, updatedJson);
}
Upvotes: 3