C# 保存到文本文件中的多行

标签 c# .net file save

我一直在为一个大学项目这样做,但遇到了问题。我已设法从文件中加载多行,但无法将它们保存回文件中。我可以将单个字符串保存到文件中,这是最后处理的字符串,但仅此而已。我可能通过执行循环来完全错误地做到这一点,但我想不出任何其他方法来做到这一点。 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/

相关文章:

c# - Winforms:Winforms 应用程序的键盘快捷键在其面板中托管其他应用程序

c# - if语句的解释

python - 在 Python 中的两个给定路径之间查找公共(public)文件的有效方法

javascript - 触发鼠标单击 Canvas 上的输入类型按钮

php - 复制文本文件的内容并插入到数据库表中,其中给定列等于文本文件的标题

c# - Dapper - 如何使用动态对象

c# - 如何在C#.Net中使用反射(指定多少层次结构)来获取类的属性?

.net - 在 64 位环境中使用 32 位 COM 对象

c# - 无法在powershell脚本中调用IFileSystemOperations.Open()方法

C#:涉及空引用时重载 == 运算符的最佳实践