我正在使用C#操作csv文件,但我遇到了问题。当我添加新行时,第一次迭代成功,但第二次迭代覆盖前一行。
CSV文件示例:
姓名,姓氏,年龄
大卫,托德,28岁Juan,Perez,30岁
第一次迭代:
姓名,姓氏,年龄
大卫,托德,28岁Juan,Perez,30岁
Pepe,Hernandez,32岁
第二次迭代:
姓名,姓氏,年龄
大卫,托德,28岁Juan,Perez,30岁
Pepe,Hernandez,32Maria,Lopez,35
我做错了什么?
这是我的代码:
string newFileName = "C:\\names.csv";
string nameDetails = txtName.Text + "," + txtLastName.Text + "," + txtAge.Text;
if (!File.Exists(newFileName))
{
string nameHeader = "Name" + "," +
"LastName" + "," + "Age" + Environment.NewLine;
File.WriteAllText(newFileName, nameHeader);
}
File.AppendAllText(newFileName, nameDetails);
谢谢!
答案 0 :(得分:1)
只需将您的代码更改为以下内容:
string newFileName = "C:\\names.csv";
string nameDetails = txtName.Text + "," + txtLastName.Text + "," + txtAge.Text;
if (!File.Exists(newFileName))
{
string nameHeader = "Name,LastName,Age\n"; //No point concatenating
nameDetails = nameHeader + nameDetails;
}
File.AppendAllText(newFileName, nameDetails);
旁注:
使用string.Format
可以使事情更加整洁。如果你这样做,你的代码就会变成这样:
string newFileName = "C:\\names.csv";
string nameDetails = string.Format("{0},{1},{2}\n", txtName.Text, txtLastName.Text, txtAge.Text);
if (!File.Exists(newFileName))
{
nameDetails = "Name,LastName,Age\n" + nameDetails;
}
File.AppendAllText(newFileName, nameDetails);
如果您使用的是最新的 c#6 ,事情可以变得更好:
string newFileName = "C:\\names.csv";
string nameDetails = $"{txtName.Text},{txtLastName.Text},{txtAge.Text}\n");
if (!File.Exists(newFileName))
{
nameDetails = "Name,LastName,Age\n" + nameDetails;
}
File.AppendAllText(newFileName, nameDetails);
答案 1 :(得分:1)
你错过了
+ Environment.NewLine
打电话
File.AppendAllText
它也应该存在,即它应该是
File.AppendAllText(newFileName, nameDetails + Environment.NewLine);