简体   繁体   English

使用C#将列表保存到文本文件中

[英]Save List into a text file using C#

I am developing an Address Book using C#. 我正在使用C#开发通讯簿。

i have a list which is displayed in an DataGridView but I want to save the list and not the datagridview into a text file. 我有一个显示在DataGridView中的列表,但是我想将列表而不是datagridview保存到文本文件中。

When the form loads i have the code: 当表单加载时我有代码:

string[] parts = line.Split(','); // the word line throws an error saying that it does not exist in the current context
Person p = new Person(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]);
AddressBook.Persons.Add(p);

I then have this code in the datalayer to save the list: 然后,我在数据层中保存以下代码以保存列表:

string filePath = @"c:\test.txt";
p.ToString(); // it does not recognise p

Can anyone help? 有人可以帮忙吗?

A simple and easy to use method for writing into a file is File.WriteAllText( filePath, p.ToString()). 一种简单易用的写入文件的方法是File.WriteAllText(filePath,p.ToString())。 You have also to override the method ToString in the class Person, so you can return the information you want to save to file, otherwise it will, as default, return the class' name as string. 您还必须重写类Person中的ToString方法,以便可以返回要保存到文件中的信息,否则默认情况下,它将以字符串形式返回类的名称。 If you need a speedest way you should use a StreamWriter. 如果您需要最快的方法,则应使用StreamWriter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM