C#保存到一个文本文件中多行 [英] C# save to multiple lines in a text file
问题描述
我一直在这样做了大学的项目,并遇到了一个问题。我已成功地从文件加载多行,但我无法将它们保存回一个文件中。我还能再救一个字符串的文件,这是处理的最后一个字符串,但就是这样。我会那样做完全执行循环不对,但我想不出任何其他方式做到这一点。对于saveFile的部分编码如下:
I have been doing this for a university project and have run into a problem. I have managed to load multiple lines from a file but I am unable to save them back to a file. I can save a single string to the file, which is the last string processed but that is it. I may be doing it completely wrong by performing a loop, but I cant think of any other way to do it. The coding for the savefile section is as follows:
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;
}
不知道从哪里何去何从。任何帮助,将不胜感激。
Not sure where to go from here. Any help would be appreciated
推荐答案
您应该打开文件保存的前的循环。例如:
You should open the file for saving before the loop. E.g.
using (StreamWriter save = new StreamWriter("billing.txt")) {
while (savecount != CustomerCount) {
// rest of your code here
目前,您正在打开在每个循环中的文件,写一个线路输出。然后重新打开它(和丢失已写入的数据)。
At the moment, you are opening the file in each loop, writing a line out. Then re-opening it (and losing the data already written).
正如评论指出的那样,你不需要调用文件.Create
。默认情况下,的StreamWriter
将覆盖现有文件。
As pointed out in the comments, you don't need to call File.Create
. By default the StreamWriter
will overwrite the existing file.
这篇关于C#保存到一个文本文件中多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!