我正在做一个小家庭项目,以了解有关集合和 FileIO 的更多信息。
我制作了一个小赛车应用程序,用户在其中输入所有都是字符串的赛车手详细信息,并将这些详细信息插入到列表列表中,然后一旦用户单击“保存”按钮,列表的内容就会被提取为文本文件。我已经成功地能够写入文本文件,但是我现在想更改它,以便我能够将数据附加到文本文件而不是每次将数据写入文本文件时覆盖以前的数据,我是在使用 AppendAllText() 时遇到此问题。
以下是我的 People 类如何处理列表中的数据输入:
class People
{
public string Name { get; set; }
public string Car { get; set; }
public string Place { get; set; }
public List<string> myList = new List<string>();
public void ShowList()
{
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine("" + myList[i] + "\n|");
}
}
public void AddToList()
{
myList.Add("Name: " + Name + " Car: " + Car + " Place: " + Place);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 Form1 类,其 main 方法处理事件并将值发送到 People 类中的列表:
public partial class Form1 : Form
{
People person = new People();
string path = @"C:\Users\Keil\Documents\Visual Studio 2013\Projects\CarRacingArrList\racers.txt";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
person.ShowList();
}
private void button2_Click(object sender, EventArgs e)
{
person.Name = textBox1.Text;
person.Car = textBox2.Text;
person.Place = textBox3.Text;
person.AddToList();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
File.AppendAllText(path, person.myList.OfType<string>().ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在使用 AppendAllText() 方法,在该方法中我传递了文本文件的路径和列表的内容。当数据写入文本文件时,它会将其附加到末尾:System.Linq.Enumerable+d__aa`1[System.String] 而不是存储在 myList 中的实际数据。
看起来是返回对象类型而不是实际数据
我的代码中是否缺少某些内容?
不要叫ToString后OfType。使用string.Join来连接所有线路。
File.AppendAllText(path, string.Join(Environment.NewLine, person.myList));
Run Code Online (Sandbox Code Playgroud)
或者只是使用 File.AppendAllLines
File.AppendAllLines(path, person.myList);
Run Code Online (Sandbox Code Playgroud)
我也删除了这个OfType电话,因为它是多余的,你已经有了 List<string>
| 归档时间: |
|
| 查看次数: |
3502 次 |
| 最近记录: |