当表单退出时关闭 Stream Read 和 Stream Writer [英] Closing Stream Read and Stream Writer when the form exits

查看:39
本文介绍了当表单退出时关闭 Stream Read 和 Stream Writer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,这里有点麻烦.

Hey guys, having a bit of trouble here.

所以我有一个加载按钮来加载文件,还有一个保存按钮来保存文件.我还有一个关闭程序的退出按钮.我需要帮助的是,当我关闭程序时,我不会检查是否有任何未关闭的StreamReader或StreamWriter东西.

So I have a load button that loads the file, and a save button the saves the file. I also have a exit button that closes the program. What I need help with is when I close the program, I wont to check whether there are any StreamReader or StreamWriter things that have not been closed.

这是我目前所拥有的:在顶部,我清楚这些家伙

Heres what I have so far: At the top, i declear these guys

    bool isDirtyBoolean = false;
    string moreData = "";

我的加载按钮看起来像这样

My load button looks like this

    private void loadToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //begin in the project folder
        openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();

        //display the file open dialog box
        DialogResult responseDialogResult;
        responseDialogResult = openFileDialog1.ShowDialog();

        if (responseDialogResult != DialogResult.Cancel)
        {   //check that user did not click the cancel button
            //create a streamreader object for the selected file, 
            //read the file contents,
            //and display each line of the file in the list box

            StreamReader nameStreamReader = new StreamReader(openFileDialog1.FileName);

            while (nameStreamReader.Peek() != -1)
            {
                freindsDataListBox.Items.Add(nameStreamReader.ReadLine());

            }

            nameStreamReader.Close();
            isDirtyBoolean = true;
        }
    }

我的保存按钮看起来像这样

And my save button looks like this

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //begin in the project folder
        saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();

        //display the file save dialog 
        DialogResult responseDialogResult;
        responseDialogResult = saveFileDialog1.ShowDialog();

        if (responseDialogResult != DialogResult.Cancel)
        {   //check that user did not click the cancel button
            //create a streamWriter object and 
            //then write out the list box items to the file

            StreamWriter nameStreamWriter = new StreamWriter(saveFileDialog1.FileName);

            int count = freindsDataListBox.Items.Count;
            for (int i = 0; i < count; i++)
            {
                nameStreamWriter.WriteLine(freindsDataListBox.Items[i]);
            }

            nameStreamWriter.Close();
            isDirtyBoolean = true;
            freindsDataListBox.Items.Clear();
        }
    }

我的退出按钮是这样的

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (isDirtyBoolean == false)
            nameStreamReader.Close();
            nameStreamWriter.Close();

        this.Close();
    }

我试图做的是在顶部设置 bool isDirtyBoolean,然后当 Stream Reader 或 Writer 关闭时,将 bool 值设置为 true,所以当我退出应用程序时,如果它仍然设置为 false,它会关闭它们无论如何.

What I tried to do was set up the bool isDirtyBoolean up top, then when the Stream Reader or Writer closes, sets the bool value to true, so when i exit the app, if its still set to false, it closes them anyway.

但这不起作用,因为 isDirtyBoolean 值是那些私有的无效按钮,我无法访问它们.

But this doesnt work because the isDirtyBoolean value is those private void buttons and I cant get to them.

推荐答案

为了更好地跟踪一般情况,请使用打开它们的相同方法关闭读者和作者,而不是让它们在整个过程中继续存在应用.

To keep better track of things in general, close your readers and writers in the same method you open them in, rather than letting them live for the duration of the application.

如果您使用 using,它们将被自动处理(并关闭).示例:

If you use using they will be disposed of (and closed) automatically. Examples:

读者:

using (StreamReader reader = new StreamReader(openFileDialog1.FileName)) {

    // do your stuff...

} // automatic close.

您可以对编写器实例执行相同操作.

You can do the same with your writer instance.

或者,如果您同时阅读和写作,您可以像这样同时打开并自动关闭两者:

Or if you're reading and writing at the same time you can open both and auto-close both at the end like so:

using (StreamReader reader = new StreamReader(openFileDialog1.FileName)) {
    using (StreamWriter writer = new StreamWriter(path_to_other_file)) {

        // now you're reading and writing

        // DO YOUR STUFF

    } // closes writer.
} // closes reader.

using 之所以能正常工作是因为 IDisposable 接口,由流读取器和写入器类实现;事实上,任何实现这个接口的类都是使用 using 语句的候选者.

The reason using works as it does is because of the IDisposable interface which is implemented by both the stream reader and writer classes; in fact any class implementing this interface is a candidate for using the using statement on.

记住要留意 MSDN 文档中的警告,如下所示:

And remember to keep an eye out for caveats in the MSDN documentation like so:

StreamWriter.Dispose总是关闭流

StreamWriter.Dispose 总是关闭流处置 StreamWriter 关闭底层流处置,即使您使用构造函数,你明确地提供流.有时你想要保持流打开,但是这类目前不提供这样做的机制,除了不调用 Dispose,但一定要调用代替冲洗.

StreamWriter.Dispose always closes stream Disposing a StreamWriter closes the underlying stream when it is disposed, even if you use a constructor where you explicitly provide the stream. Sometimes you want to keep the stream open, but this class doesn't currently provide a mechanism to do that, except to not call Dispose, but be sure to call Flush instead.

这篇关于当表单退出时关闭 Stream Read 和 Stream Writer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆