我正在使用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);
}
如果你認爲foreach是否有什麼納稅人? – 2014-12-07 06:17:41
你應該使用'using'語句來處理一次性東西。但是,假設你的代碼在沒有任何異常被拋出的情況下執行,那麼你的文件可能爲空的唯一方式是,如果你正在查看錯誤的文件,或者「納稅人」集合是空的。 – 2014-12-07 06:20:25