【发布时间】:2013-12-07 09:31:07
【问题描述】:
我有一个主窗口,用户单击一个按钮来处理选定的输入文件。按钮触发的代码块打开输入文件、输出文件和日志文件。相同的代码块一次读取输入文件的一行,对每行中的字段执行一些操作,然后将相应的行写入输出文件。错误消息被写入日志文件。处理单个文件可能需要几分钟时间。
如果用户不耐烦并使用红色的“X”按钮关闭主窗口,我希望能够优雅地关闭这 3 个文件。我有一个捕获单击“X”的事件处理程序,但我无法引用我要关闭的 3 个文件流,因为它们是在事件处理程序的上下文之外创建的。如何将 3 个文件流传递给处理程序?
namespace less
{
public partial class MainWindow : Window
{
...
private static string filename;
...
public MainWindow()
{
InitializeComponent();
// string filename is chosen in this block of code
}
private void convertData_Click(object sender, RoutedEventArgs e)
{
// This is invoked when user clicks the "Process Data" button
System.IO.StreamReader inputFile = new System.IO.StreamReader(filename);
System.IO.StreamWriter outputFile = new System.IO.StreamWriter(filename + ".less.csv");
System.IO.StreamWriter logFile = new System.IO.StreamWriter(filename + ".log");
....
<process all the data>
....
inputFile.Close(); // <- this works
outputFile.Close(); // <- this works
logFile.Close(); // <- this works
this.Close();
}
private void MainWindow_Closed(object sender, EventArgs e)
{
// This is the event handler invoked when the red "X" is clicked.
inputFile.Close(); // <- this (and following) do not work
outputFile.Close();
logFile.Close();
}
} // closes public partial class MainWindow : Window
} // closes namespace
【问题讨论】:
-
您是否尝试过处理对象,而不仅仅是关闭它们?创建实现 IDisposable 的对象时,您应该使用 using 语句。
标签: c# filestream