i need to save data in list which i input in console.I have 3 function`Show(),Add(),Delete(). When i input 1 it must show me my data's list,when i input 2 it must ask me "Enter new user's data with comma",for example` John,25,then it must be saved in my list, that's to say when i input 1 it must show me my list + new adding data, and when i input 3 it must ask me "Please type the index of Person, whom you want to delete",for example i will input 2 and it must delete second index person, and then when i input 1 it must show me my list without second index person.
But in my code it's not working, after adding or deleting it's not show me that person whom i added or deleted.
Please help me,What's my mistake???????
What I have tried:
class Controller
{
public List<Person> all;
public void Show()
{
string path = "C:/Users/User/Desktop/mardik.txt";
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
List<Person> all = bf.Deserialize(fs) as List<Person>;
foreach (Person item in all)
{
Console.WriteLine(item.name + " " + item.age);
}
fs.Close();
}
public void Add()
{
string path = "C:/Users/User/Desktop/mardik.txt";
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
BinaryFormatter bf = new BinaryFormatter();
List<Person> all = bf.Deserialize(fs) as List<Person>;
Console.WriteLine("Enter new user's data with comma");
string text = Console.ReadLine();
string[] segments = text.Split(',');
string a = segments[0];
int b;
bool hajoxvec = int.TryParse(segments[1], out b);
if (!hajoxvec)
{
Console.WriteLine("Please try again");
this.Add();
}
else
{
all.Add(new Person(a, b));
}
foreach (Person item in all)
{
Console.WriteLine(item.name + " " + item.age);
}
fs.Close();
}
public void Delete()
{
string path = "C:/Users/User/Desktop/mardik.txt";
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
BinaryFormatter bf = new BinaryFormatter();
List<Person> all = bf.Deserialize(fs) as List<Person>;
Console.WriteLine();
Console.WriteLine("Please type the index of Person, whom you want to delete");
int num = int.Parse(Console.ReadLine());
if (num < 0 || num > 4)
{
Console.WriteLine("Please try again");
this.Delete();
}
else
{
all.RemoveAt(num);
}
foreach (Person item in all)
{
Console.WriteLine(item.name + " " + item.age);
}
fs.Close();
}
}
[Serializable]
class Person
{
public string name;
public int age;
public Person(string a, int b)
{
this.name = a;
this.age = b;
}
}
static void Main(string[] args)
{
string path = "C:/Users/User/Desktop/mardik.txt";
Controller c = new Controller();
while (true)
{
Console.WriteLine();
Console.WriteLine("Incheq uzum anel:\n1.Show all People\n2.Add new person\n3.Delete any person");
int x = int.Parse(Console.ReadLine());
switch (x)
{
case 1:
c.Show();
break;
case 2:
c.Add();
break;
case 3:
c.Delete();
break;
}
}
}