如何使用switch-case将列表中的数据添加到.txt文件中 [英] How to add data in list to .txt file with switch-case

查看:121
本文介绍了如何使用switch-case将列表中的数据添加到.txt文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Controller和Person类,我需要在列表中添加数据,添加到Console的所有数据都必须存储在.txt文件中。也就是说,如果用户输入1来查看数据,那么必须从文件中读取然后显示,当用户输入2添加新数据时,必须从文件中读取然后显示。

i已经编写了Show()函数,它正在工作,但是add()函数不起作用,我有什么错误?



我尝试过:



i have Controller and Person classes,i need to add data in my list,All data that is added to the Console must be stored in a .txt file.That is, if the user inputs 1 to see the datas, it must be read from the file then displayed, when the user inputs 2 to add new data,it must be read from the file then displayed.
i have already written the Show() function,it's working,but add() function doesn't work,what's false i have?

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);
            }
        }
        public void Add()
        {
            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>;
            
            Console.WriteLine("Enter new user's data");
            string text = Console.ReadLine();
            
            foreach(Person item in all)
            {
                Console.WriteLine(item.name + " " + item.age);
            }
        }





我在Add()函数中的错误是什么?





What is my Mistake in Add() function?

[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";
            List<Person> mardik = new List<Person>();
            //mardik.Add(new Person("Valod", 20));
            //mardik.Add(new Person("Petros", 23));
            //mardik.Add(new Person("Poghos", 25));
            //mardik.Add(new Person("Hranush", 22));
            //mardik.Add(new Person("Suren", 18));
            //FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            //BinaryFormatter bf = new BinaryFormatter();
            //bf.Serialize(fs, mardik);
            //fs.Close();
            Controller c = new Controller();
            while (true)
            {
                Console.WriteLine();
                Console.WriteLine("What do you want to do:\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;
                    
                }
            }
        }

推荐答案

这里有几件事情:

1)不要硬编码路径,而是使用配置文件 - 如果你不能解决这个问题,那么使用const值,这样你只需要在一个地方改变它。

2)如果你打开一个文件或流,你负责关闭和处理它:你的代码都不会这样做,这意味着在应用程序关闭或垃圾收集器被踢入之前,流保持打开状态在你之后清理。如果文件是打开的,你可以打开它进行写作!

3)你的add方法从用户读取数据,但对它没有任何作用:它在方法结束时被丢弃,因此,首先阅读它没什么意义!

4)当你使用BinaryFormatter时,使用.TXT扩展名会产生误导 - 它意味着人类可读和可编辑的内容,而BinaryFormatter不会产生这种内容。

5)永远不要相信用户输入: int.Parse 会抛出一个异常是用户输入hello或A而不是a数字。我建议你改用 int.TryParse



我建议你看看在Streams和Formatters周围使用块,并考虑将用户的新数据作为Add方法的一部分附加到文件中,并以某种方式显示它。
Couple of things here:
1) Don't hardcode paths, use a config file instead - and if you can't work that out, then use a const value so you only have to change it in one place.
2) If you open a file or stream, you are responsible for closing and Disposing of it: none of your code does that, which means the stream remains open until either the app closes or the Garbage Collector gets kicked in to clean up after you. If a file is open, you can;t open it for writing!
3) Your add method reads data from the user, but does nothing with it: it is discarded at the end of the method, so there is little point in reading it in the first place!
4) Using the .TXT extension is misleading when you use a BinaryFormatter - it implies human readable and editable content, which a BinaryFormatter does not produce.
5) Never trust user input: int.Parse will throw an exception is the user enters "hello" or "A" instead of a digit. I'd suggest you use int.TryParse instead.

I'd suggest that you look at using blocks around your Streams and Formatters, and that you look at appending the new data from the user to your file as part of you Add method, as well as displaying it in some way.


public void Add()
        {
            const 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>;
            fs.Close();
            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();
        }





它正在工作,现在我只需要保存我的添加数据。



it's working, now i need only to save my adding data.


这篇关于如何使用switch-case将列表中的数据添加到.txt文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆