✅ Storing information

What is the best way to save/load information on startup and closing program?
13 Replies
Jimmacle
Jimmacle4w ago
there is no one best way, but if you just want a suggestion to start with you can use System.Text.Json to convert a C# object to and from text and store it in a file there are different formats, databases, etc that may be more or less appropriate depending on the details of what you're trying to do
monkeyoohlala
monkeyoohlalaOP4w ago
No description
monkeyoohlala
monkeyoohlalaOP4w ago
I basically have to store 4 strings as 1 object and I have to edit and save the file on a button click event
Jimmacle
Jimmacle4w ago
my suggestion is probably your best option then, assuming your course doesn't have any restrictions on how to do it or what libraries you can use
monkeyoohlala
monkeyoohlalaOP4w ago
I will try it I will create a backup of my project first I checked microsoft learn and they dont have anything there on json am I supposed to be using Newtonsoft.Json?
Sehra
Sehra4w ago
in general, go with System.Text.Json nowadays
monkeyoohlala
monkeyoohlalaOP4w ago
is newtonsoft the same as regular json? are there any free tutorials you can recommend? I know what json does but have not really used it before when I was doing java
Sehra
Sehra4w ago
newtonsoft.json is just a library to work with json, it was the common one before system.text.json was added to .net
monkeyoohlala
monkeyoohlalaOP4w ago
oh okay I need to find a tutorial on that
Sehra
Sehra4w ago
Serialize and deserialize JSON using C# - .NET
This overview describes the System.Text.Json namespace functionality for serializing to and deserializing from JSON in .NET.
monkeyoohlala
monkeyoohlalaOP4w ago
ay ay captain are there any dangers in using json?
var jsonString = JsonSerializer.Serialize(newAccount);
var fileName = "Data.json";
File.AppendAllText(fileName, jsonString);
var jsonString = JsonSerializer.Serialize(newAccount);
var fileName = "Data.json";
File.AppendAllText(fileName, jsonString);
var fileName = "Data.json";
if (File.Exists(fileName))
{
string json = File.ReadAllText(fileName);
List<Account> accounts = JsonSerializer.Deserialize<List<Account>>(json);
foreach (var account in accounts)
{
ListAccounts.Add(account);
}
}
var fileName = "Data.json";
if (File.Exists(fileName))
{
string json = File.ReadAllText(fileName);
List<Account> accounts = JsonSerializer.Deserialize<List<Account>>(json);
foreach (var account in accounts)
{
ListAccounts.Add(account);
}
}
my program wont start
Jimmacle
Jimmacle4w ago
when you say it won't start what does that mean exactly
monkeyoohlala
monkeyoohlalaOP4w ago
got it working sort of

Did you find this page helpful?