我一直在为一个大学项目这样做,但遇到了问题。我已设法从文件中加载多行,但无法将它们保存回文件中。我可以将单个字符串保存到文件中,这是最后处理的字符串,但仅此而已。我可能通过执行循环来完全错误地做到这一点,但我想不出任何其他方法来做到这一点。 savefile部分的编码如下:
case "s":
case "8":
{
int savecount = 0;
string savestring = "";
//Clear the text file ready to be saved
using (FileStream fs = File.Create("billing.txt"))
{
}
while (savecount != CustomerCount)
{
using (StreamWriter save = new StreamWriter("billing.txt"))
{
//Create the string to save to the file
savestring = CustomerNumber[savecount] + ","
+ CustomerName[savecount] + ","
+ Address[savecount] + ","
+ RateScheme[savecount] + ","
+ PeakKWH[savecount] + ","
+ OffPeakKWH[savecount] + ","
+ StandardKWH[savecount];
Console.WriteLine(savestring);
save.WriteLine(savestring);
savecount++;
Console.ReadLine();
}
}
Console.WriteLine("All data saved successfully");
Console.ReadLine();
break;
}
不知道从这里去哪里。任何帮助将不胜感激
最佳答案
您应该在循环之前打开用于保存的文件。例如
using (StreamWriter save = new StreamWriter("billing.txt")) {
while (savecount != CustomerCount) {
// rest of your code here
目前,您在每个循环中打开文件,写出一行。然后重新打开它(并丢失已写入的数据)。
正如评论中所指出的,您不需要调用File.Create
。默认情况下,StreamWriter
将覆盖现有文件。
关于C# 保存到文本文件中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19315921/