使用streamwriter但文件始终为空

时间:2014-12-07 06:13:53

标签: c# streamwriter

我正在使用Streamwriter将列表数据保存到文本文件中,但是当我打开文件时,该文件始终为空。 我可以让列表显示所有输入,因此列表有效。下面是文件编写者的代码。

private void SaveToFile()
    {
        string taxpayerLine;
        string taxpayerFile;
        string myFileName;
        FileInfo myFile;
        SaveFileDialog taxpayerFileChooser;

        StreamWriter fileWriter;


        taxpayerFileChooser = new SaveFileDialog();
        taxpayerFileChooser.Filter = "All text files|*.txt";
        taxpayerFileChooser.ShowDialog();
        taxpayerFile = taxpayerFileChooser.FileName;
        taxpayerFileChooser.Dispose();

        fileWriter = new StreamWriter(taxpayerFile, true);

        foreach (Taxpayer tp in Taxpayers)
        {
            taxpayerLine = tp.Name + "," +
                tp.Salary.ToString() + "," +
                tp.InvestmentIncome.ToString() + "," +
                (tp.InvestmentIncome + tp.Salary).ToString() + "," +
                tp.GetRate().ToString() + "," +
                tp.GetTax().ToString();

            fileWriter.WriteLine(taxpayerLine);
        }

        fileWriter.Close();
        fileWriter.Dispose();

        myFile = new FileInfo(taxpayerFile);
        myFileName = myFile.Name;

        MessageBox.Show("Data Saved to " + myFileName);
    } 

1 个答案:

答案 0 :(得分:1)

您可以尝试更改代码,如下所示:

private void SaveToFile()
{
    string taxpayerLine;
    string taxpayerFile = string.Empty;
    string myFileName;
    FileInfo myFile;

    using (SaveFileDialog taxpayerFileChooser = new SaveFileDialog())
    {
        taxpayerFileChooser.Filter = "All text files|*.txt";
        if (DialogResult.OK == taxpayerFileChooser.ShowDialog())
        {
            taxpayerFile = taxpayerFileChooser.FileName;
        }
    }

    if (!string.IsNullOrEmpty(taxpayerFile))
    {
        using (StreamWriter fileWriter = new StreamWriter(taxpayerFile, true))
        {
            foreach (Taxpayer tp in Taxpayers)
            {
                taxpayerLine = tp.Name + "," +
                tp.Salary.ToString() + "," +
                tp.InvestmentIncome.ToString() + "," +
                (tp.InvestmentIncome + tp.Salary).ToString() + "," +
                tp.GetRate().ToString() + "," +
                tp.GetTax().ToString();

                fileWriter.WriteLine(taxpayerLine);
            }
        }

        myFile = new FileInfo(taxpayerFile);
        myFileName = myFile.Name;

        MessageBox.Show("Data Saved to " + myFileName);
    }
    else
    {
        MessageBox.Show("Data not saved");
    }
}

using语句显式在块执行后调用一次性对象的Dispose()方法。 http://msdn.microsoft.com/en-us/library/yh598w02.aspx