0

我正在尝试在表单关闭事件中将一些字符串写入文本文件。问题是 streamwriter 不写任何东西,它只是写了一个空白。我有 2 个不同的文本文件,第一个将记录所有图形数据,第二个文本文件将记录一些与我的应用程序相关的首选项。我的代码如下所示,用于关闭事件和单独的主力方法:

  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {


        if (e.CloseReason.Equals(CloseReason.WindowsShutDown) || (e.CloseReason.Equals(CloseReason.UserClosing))) 
        {
            if (MessageBox.Show("You are closing this application.\n\nAre you sure you wish to exit ?", "Warning: Not Submitted", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes)
            {

                writeContents("Interrupted");

                return;
            }

            else
                e.Cancel = true; 
        } 



    }

    private void writeContents(string status)
    {

        //---writes the graph data-----
        TextWriter twBackupData = new StreamWriter("C://springTestBackupData.txt");

        twBackupData.WriteLine("--Cycle#-- --TorqueLower-- --TorqueUpper--");

        //writes the table of values in there, assume x and y are the same size arrays
        for(int i = 0; i < x.Count; i++)
        {               
            twBackupData.WriteLine(x[i] + "   " + y_lower[i] + "   " + y_upper[i]);
        }


        //---writes some of the preferences------
        TextWriter twBackupDataInfo = new StreamWriter("C://springTestBackupInfo.txt");

        twBackupDataInfo.WriteLine(status);
        twBackupDataInfo.WriteLine(cycleCount.ToString());
        twBackupDataInfo.WriteLine(section.ToString());
        twBackupDataInfo.WriteLine(revsPerCycle.ToString());
        twBackupDataInfo.WriteLine(preturns.ToString());
        twBackupDataInfo.WriteLine(direction.ToString());

    }

如果您能提供建议或帮助我找出为什么它写空白,我将不胜感激。谢谢!

4

4 回答 4

2

您需要关闭StreamWriterusingusing语句。

于 2012-05-16T16:10:32.560 回答
1

使用起来要容易得多:

var linesToWrite = new list<string>();

linesToWrite.Add(status);
linesToWrite.Add(cycleCount.ToString());
...

File.WriteAllLines("C://springTestBackupData.txt", linesToWrite);
于 2012-05-16T16:11:25.350 回答
1

您需要关闭/处置写入器以使其写入,否则它永远不会刷新其流(即将数据写入文件)

使用 'using' 语句会在对象超出范围时自动处理它,因此:

using(TextWriter twBackupData = new StreamWriter("C://springTestBackupData.txt"))
{
     // Do your stuff here - write to the tw ---


    twBackupData.WriteLine("--Cycle#-- --TorqueLower-- --TorqueUpper--");   

    //writes the table of values in there, assume x and y are the same size arrays   
    for(int i = 0; i < x.Count; i++)   
    {                  
        twBackupData.WriteLine(x[i] + "   " + y_lower[i] + "   " + y_upper[i]);   
    }   
}

将确保您的文件被写入

更多信息在这里:

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

于 2012-05-16T16:12:31.997 回答
0

你需要.Close()在你的 StreamWriters 上做;

于 2012-05-16T16:10:57.927 回答