C# save to multiple lines in a text file

十年热恋 提交于 2020-01-04 06:53:47

问题


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


回答1:


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).

As pointed out in the comments, you don't need to call File.Create. By default the StreamWriter will overwrite the existing file.




回答2:


You need the while loop inside the using { } As it is you're overwriting your data each time, leaving the last item in your file when you look at it:

using (StreamWriter save = new StreamWriter("billing.txt"))
{
     while (savecount != CustomerCount)
     {
       //Create the string to save to the file
       string savestring = CustomerNumber[savecount] + ","
       + CustomerName[savecount] + ","
       + Address[savecount] + ","
       + RateScheme[savecount] + ","
       + PeakKWH[savecount] + ","
       + OffPeakKWH[savecount] + ","
       + StandardKWH[savecount];

       Console.WriteLine(savestring);

       save.WriteLine(savestring);

       savecount++;
       Console.ReadLine();
   }
}



回答3:


What You are doing wrong is, you are opening the file in each iteration of while, writing a line in file and Then again re-opening the file and overwriting the contents. You can rechange your code

using (StreamWriter save = new StreamWriter("billing.txt")) 
{
   while (savecount != CustomerCount) 
   { 
     // rest of string formation of saveString logic and save.WriteLine(savestring); goes here
     .....
   }
}

I think you can use a simple code also where you can save all your input string in an List and use File.WriteAllLines function as

     {
       ....   
        List<string> Customers = new List<string>();
        for (savecount = 0; savecount < CustomerCount; savecount++)
        {            
         //Create the string to save to the file
            Customers.Add( CustomerNumber[savecount] + "," + CustomerName[savecount] + "," + Address[savecount] + "," + RateScheme[savecount] + "," + PeakKWH[savecount] + "," + OffPeakKWH[savecount] + "," + StandardKWH[savecount]);

            Console.WriteLine(Customers[savecount]);
        }

        string filePath = "billing.txt"; // This is your file path where all the contents are to be written
        File.WriteAllLines(filePath, Customers);
       ..........
     }



回答4:


You need:

using (StreamWriter save = new StreamWriter("billing.txt")) {
    while (savecount != CustomerCount) {

You have to open file before loop because opening inside deletes all previous data written in that, also it takes some time for opening.

However you can open file inside loop, but you need to set append file, it would be:

StreamWriter save = new StreamWriter("billing.txt", true)

This option is slower and you may need to clear file before opening in append mode, so it isn't the best option.



来源:https://stackoverflow.com/questions/19315921/c-sharp-save-to-multiple-lines-in-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!