2012-05-16 49 views
0

我正在尝试将一些字符串写入formclosing事件上的文本文件。问题是,Streamwriter不写任何东西,它只是写一个空白的石板。我有两个不同的文本文件,第一个将记录所有图形数据,第二个文本文件将记录与我的应用程序相关的一些偏好。我的代码如下所示的两个关闭事件和一个单独的主力方法:在窗体关闭事件中写入文本文件

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()); 

    } 

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

+0

尝试StreamWriter.Flush(),然后StreamWriter.Close() –

+3

我想'.Close'实际上是调用'.Flush'为好。 –

回答

2

您需要使用using声明关闭StreamWriter

0

您需要在StreamWriters上执行.Close();

1

这是很容易,只需使用:

var linesToWrite = new list<string>(); 

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

File.WriteAllLines("C://springTestBackupData.txt", linesToWrite); 
1

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

自动使用“使用”声明的对象的处置当它超出范围如此:

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