I'm new to C# and as my first "program", I want to build a ToDo-list app that runs in console.
I've laid down the basic frame of the program, but I do not seem to find how to save user data outside of the main code and so that it can be referenced again in the next session.
I do not want to save the tasks as variables temporarily.
My idea how my app would work is that if I open the program and I have the choice to either write/add a task or read the tasks.
If I write a new task the console should display the updated ToDo list with the newest task in addition to tasks i added in past sessions.
Right now I don't plan to add a "delete task" button, maybe after I understand how to solve the first problem. I am using VisualStudio for mac if that is relevant.
CodePudding user response:
There are many ways this can be done.
One of the easiest and most commonly used is with JSON.
Here is a complete program I wrote so that you can experiment with.
public class TodoItem
{
public string Description { get; set; }
public DateTime? DueOn { get; set; }
public override string ToString()
{
return $"{this.Description}";
}
}
internal static class Program
{
static private readonly string _saveFileName = "todo.json";
static void Main()
{
{
// An example list containing 2 items
List<TodoItem> items = new List<TodoItem> {
new TodoItem { Description = "Feed the dog" },
new TodoItem { Description = "Buy groceries", DueOn = new DateTime(2021, 9, 30, 16, 0, 0) }
};
// Serialize it to JSON
string json = JsonSerializer.Serialize(items, new JsonSerializerOptions() { WriteIndented = true });
// Save it to a file
File.WriteAllText(_saveFileName, json);
}
// Now we'll load the list back from the file
{
string json = File.ReadAllText(_saveFileName);
List<TodoItem> items = JsonSerializer.Deserialize<List<TodoItem>>(json);
// Check whether the list has loaded correctly
foreach (var todo in items)
Console.WriteLine(todo);
}
}
Program output:
Feed the dog
Buy groceries
todo.json
file contents:
[
{
"Description": "Feed the dog",
"DueOn": null
},
{
"Description": "Buy groceries",
"DueOn": "2021-09-30T16:00:00"
}
]
CodePudding user response:
You can store Data in a File
using System.IO;
string pathToFile = "myTodoList.txt";
string[] lines = new string[]{"task1","task2","task3");
File.WriteAllLine(pathToFile,lines);
in the txt you will find:
task1
task2
task3
and reading them:
using System.IO;
string pathToFile = "myTodoList.txt";
string[] lines = File.readAllLines(pathToFile);
foreach(string line in lines)
{
Console.ReadLine(line);
}