调用FormClosing事件但没有任何反应

时间:2017-08-11 17:30:53

标签: c#

我正在尝试在表单关闭后立即保存文件,但它无法正常工作。它显示了消息,但当我告诉程序时我想保存没有任何反应,就好像它执行了一个返回

this.FormClosing += new FormClosingEventHandler(OverrideEventClosing);

private void OverrideEventClosing(object sender, FormClosingEventArgs e) {
 DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
 if (dialogResult == DialogResult.Yes) {
  string myExePath = System.Reflection.Assembly.GetEntryAssembly().Location;
  System.IO.StreamWriter file = new System.IO.StreamWriter(@ "C:\DB.txt");

  foreach(ListViewItem cliente in listView1.Items) {
   file.WriteLine(string.Format("{0}|{1}|{2}|{3}", cliente.SubItems[0].Text, cliente.SubItems[1].Text, cliente.SubItems[2].Text, cliente.SubItems[3].Text));
  }
 }

}

2 个答案:

答案 0 :(得分:2)

写入后刷新并关闭流(在foreach之后)

答案 1 :(得分:0)

使用无法识别的行添加解决了问题

项目>添加新项>应用程序清单文件

Application Manifest File

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

并使用此

string myExePath = AppDomain.CurrentDomain.BaseDirectory;
System.IO.StreamWriter File = new System.IO.StreamWriter(myExePath + @"\item.txt");