Windows窗体保存到文件两次并附加

时间:2013-09-13 12:08:49

标签: winforms file-io save streamwriter

我正在处理一个Windows窗体项目。我有一个带有保存和退出选项的菜单条。

首次执行任一操作时,将保存文件。向用户显示一个对话框,然后他们选择文件名和路径,并保存得很好。

但是对于其他保存,由于文件已经存在,因此假设要覆盖该文件,而是将其追加到最后。因此,实际上,它会向文件输出两次相同的信息。

以下是保存和关闭的事件处理程序:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        saveCurrentFile("save");
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        saveCurrentFile("exit");
        this.Close();
    }

以下是保存方法:

private void saveCurrentFile(string sender)
    {
        // Check who called this method for the first time, if it was the save menu option, no need to ask if they want to
        // save, just show the user the prompt
        // If it was the exit menu option, ask user if they want to save
        if (sender.CompareTo("save") == 0)
        {
            if (fileName == "")
            {
                saveFileDialog1.ShowDialog();
                fileName = saveFileDialog1.FileName;
            }
        }
        else if (sender.CompareTo("exit") == 0)
        {
            // Display a messagebox to ask user if they want to save
            DialogResult dResult = new DialogResult();
            dResult = MessageBox.Show("Would you like to save?", "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

            // Check what button the user pressed
            if (dResult == DialogResult.Yes)
            {
                if (fileName == "")
                {
                    saveFileDialog1.ShowDialog();
                    fileName = saveFileDialog1.FileName;
                }
            }
        }

        // Now check if the fileName is empty
        if (fileName != "")
        {
            DateTime date = DateTime.Now;

            // Add some header information to the string builder
            sb.AppendLine("Budget Information");
            sb.Append("Date & Time File Saved: ");
            sb.AppendLine(date.ToString());
            sb.Append("\r\n");
            sb.Append("\r\n");

            // Add the income data to the string builder
            sb.AppendLine("Hourly Wage: " + hourlyUpDown.Value.ToString("C"));
            sb.AppendLine("Annual Salary: " + annualUpDown.Value.ToString("C"));
            sb.AppendLine("Tax: " + taxUpDown.Value.ToString());
            sb.AppendLine("Hours Per Week: " + hoursPerWeekUpDown.Value.ToString());
            sb.AppendLine("Weeks Per Year: " + weeksPerYearUpDown.Value.ToString());
            sb.AppendLine("Net Weekly Income: " + netWeeklyIncome.ToString("C"));
            sb.AppendLine("Net Monthly Income: " + netMonthlyIncome.ToString("C"));
            sb.AppendLine("Net Annual Income: " + netAnnualIncome.ToString("C"));

            // Add the expenses table to the string builder
            foreach (KeyValuePair<TextBox, TextBox> entry in expenses)
            {
                sb.AppendLine(entry.Key.Text + " " + entry.Value.Text);
            }

            // Add a note to the user about modifying the file by hand
            sb.Append("\r\n");
            sb.Append("\r\n");
            sb.AppendLine("This file is created in a specific format.");
            sb.AppendLine("Any modifications to it may cause errors when the program tries to open and read the file contents.");
            sb.AppendLine("Any changes made by hand must conserve the formatting");

            using (StreamWriter outfile = new StreamWriter(fileName, false))
            {
                outfile.Write(sb.ToString());
                outfile.Flush();
                outfile.Close();
            }
        }
    }

我不确定文件为什么要写两次。 我添加了outfile.Flush()outfile.Close()来尝试解决问题,但这不起作用。

任何帮助都会很棒。


编辑:我更新了代码,只使用一种方法进行保存。 这个错误比我原先想象的要复杂一点。

每次用户去保存文件时,输出都会附加到文件中。 因此,如果用户通过转到Menu-&gt;来保存文件。保存,输出将写入文件。 对于每个后续保存,都会附加输出。

不确定出了什么问题,我正在为streamwriter使用boolean append参数,刷新和关闭。

1 个答案:

答案 0 :(得分:0)

对不起伙计们,我的错误。

我忘记在写入和关闭文件后清除stringbuilder内容。

因此,在using(){}语句之后,我使用sb.Clear()清除字符串构建器,现在它可以正常工作。

只是旁注,我确实使用false boolean参数创建了流写入对象,以确保覆盖文件。