Jak stworzyć komendy typu delete, save itp

0

Witam,

Chciałbym napisać program, który będzie obsługiwał komendy takie jak

add: I prosi o podanie imię nazwisko wiek
list: wyswietla listę osób w katalogu
remove: usuwa
detail : wyświetla szczegóły osoby
open : otwiera plik. (z json i xml)
save : zapisuje plik (w json i xml)

jestem póki co na takim etapie

i moje pytanie jest następujące....
w codzie ponizej jest File i on nie posiada opcji jak np remove lub detail, add

Potrzebuje podpowiedzi typu jaka metoda, link itp
Będę wdzięczny

string path2 = @"logowanie6.txt";
Console.WriteLine("Hej! Przedstaw się. Twoje dane będą zapisane w pliku o nazwie logowanie6.txt");

if (!File.Exists(path2))
{

    using (StreamWriter sw = File.CreateText(path2))
    {
        sw.WriteLine("Osoby, które logowały się: ");

    }
}


using (StreamWriter sw = File.AppendText(path2))
{
    string namesurname = Console.ReadLine();
    sw.WriteLine(namesurname);

}
using (StreamReader sr = File.OpenText(path2))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}
3

open : otwiera plik. (z json i xml)

Z pliku wczytujesz dane do jakiejś struktury danych. Np. do List<Osoba> ( https://docs.microsoft.com/pl-pl/dotnet/api/system.collections.generic.list-1?view=net-6.0 ). Osoba to klasa z polami: imię, nazwisko, wiek.

w codzie ponizej jest File i on nie posiada opcji jak np remove lub detail, add

List<Osoba> posiada metody takie jak Add i Remove.
Detail to wypisanie pól klasy Osoba. Możesz to sobie zakodować jako przeładowanie metody ToString() (https://docs.microsoft.com/pl-pl/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method).

save : zapisuje plik (w json i xml)

Zapisujesz sobie w odpowiedni sposób wszystkie pola osób z listy osób.

list: wyswietla listę osób w katalogu

Przelatujesz pętlą for przez wczytaną/edytowaną listę osób i np. wypisujesz ich imiona i nazwiska.

2

Tutaj kilka metod:

using Newtonsoft.Json;

static List<Person> LoadList()
{
    string text = System.IO.File.ReadAllText("persons.txt");
    if (string.IsNullOrEmpty(text))
        return new List<Person>() { };
    return JsonConvert.DeserializeObject<Person[]>(text).ToList();
}
static void SaveList(IEnumerable<Person> persons)
{
    System.IO.File.WriteAllText("persons.txt", JsonConvert.SerializeObject(persons.ToArray()));
}
static void AddPerson(List<Person> list, Person newPerson)
{
    list.Add(newPerson);
}
static void RemovePerson(List<Person> list, int personId)
{
    var foundPerson = list.FirstOrDefault(x => x.Id == personId);
    if (foundPerson != null)
        list.Remove(foundPerson);
}
class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

A tutaj zarys aplikacji:

while(true)
{
    string choice = Console.ReadLine();
    switch(choice)
    {
        case "Add":
            break;
        case "Update":
            break;
        case "Remove":
            break;
        case "Exit":
            return;
    }
}
0

Po kilku godzinach stworzyłem taki kod, ale dalej nie działa jak trzeba...jak podpowiedź?



namespace TestPersonPlanet
{



    public class MyDate
    {
        public int masa { get; set; }
        public int sredni { get; set; }
        
    }

    public class Lad
    {
        public string PlanetName { get; set; }
        
        public MyDate Szczegoly { get; set; }
    }
    
  

    class Program
    {

        static void Main()
        {
            string choice = Console.ReadLine();
            //string choiceup = choice.ToUpper();
            switch (choice)
            {
                case "Add":
                    Add();
                    return;
                case "Save":
                    
                    break;
                case "List":
                    LoadList();

                    break;
                case "Exit":
                    return;
            }

           
            
            
        }
       
        public static void Add()
        {
           


            Console.WriteLine("Podaj nazwe planety");
            string name = Console.ReadLine();
            Console.WriteLine("Podaj mase");
            int masa = Convert.ToInt16(Console.ReadLine());
            Console.WriteLine("Podaj srednice");

            int sred = Convert.ToInt16(Console.ReadLine());
            
            List<Lad> _data = new List<Lad>();
            _data.Add(new Lad()

            {
                PlanetName = name,
                
                Szczegoly = new MyDate
                {
                    masa = masa,
                    sredni = sred
                    
                }
            });
            var json = System.Text.Json.JsonSerializer.Serialize(_data);
            Console.WriteLine(json);
            
            string json2 = JsonConvert.SerializeObject(_data, Formatting.Indented);
            File.AppendAllText(@"tescikkk.json", json2);
            

        }
        static List<Lad> LoadList()
        {
            string text = File.ReadAllText(@"tescikkk.json");
            if (string.IsNullOrEmpty(text))
                return new List<Lad>() { };
            return JsonConvert.DeserializeObject<Lad[]>(text).ToList();
        }


       

    }
}

1
marjar9414 napisał(a):

Po kilku godzinach stworzyłem taki kod, ale dalej nie działa jak trzeba...jak podpowiedź?

Musisz coś poprawić.

4

Szukam od kilku godzin metody/sposobu jak usunąć planetę z .json , która użytkownik napisze. jakaś sugestia?

Nie usuwaj z *.json. Usuwaj planetę z obiektu listy, po czym zapisz całą listę na dysku.

0

Użyj metod z mojego przykładu a klasę person zamień na swoją planetę. Dzięki temu będziesz mógł zrobić coś na zasadzie:

List<Planet> planets = LoadPlanets();
AddPlanet(planets, new Planet(){ ID = 1 });
AddPlanet(planets, new Planet(){ Id = 2 });
AddPlanet(planets, new Planet(){ Id = 3 });
SavePlanets(planets);
RemovePlanet(planets, 2);
SavePlanets(planets);

1 użytkowników online, w tym zalogowanych: 0, gości: 1