2

在探索创建文本文件的选项时,我偶然发现了这种我无法解释的行为

两个按钮都会创建一个文件

但是当我使用 button1 button2 创建文件时会产生错误。

这仅在实际创建文件时发生。

创建文件后,按钮 1 和 2 按预期运行

一个简单的 GUI 程序的示例代码 2 个按钮和一个包含多行文本框

    string logFile;

    public Form1()
    {
        InitializeComponent();

        logFile = "test.txt";

    }

    private void button1_Click(object sender, EventArgs e)
    {

        if (!System.IO.File.Exists(logFile))
        {
            System.IO.File.Create(logFile);
            textBox1.AppendText("File Created\r\n");
        }
        else
        {
            textBox1.AppendText("File Already Exists\r\n");
        }

        System.IO.File.AppendText("aaa");

    }

    private void button2_Click(object sender, EventArgs e)
    {

        // 7 overloads for creation of the Stream Writer

        bool appendtofile = true;

        System.IO.StreamWriter sw;

        try
        {
            sw = new System.IO.StreamWriter(logFile, appendtofile, System.Text.Encoding.ASCII);
            sw.WriteLine("test");
            textBox1.AppendText("Added To File Created if Needed\r\n");
            sw.Close();

        }
        catch (Exception ex)
        {
            textBox1.AppendText("Failed to Create or Add\r\n");

            // note this happens if button 1 is pushed creating the file 
            // before button 2 is pushed 
            // eventually this appears to resolve itself

            textBox1.AppendText("\r\n");
            textBox1.AppendText(ex.ToString());
            textBox1.AppendText("\r\n");
            textBox1.AppendText(ex.Message);
        }



    }
4

1 回答 1

4

您可能会收到错误消息,因为文件资源正在被前一个进程使用。在使用文件之类的资源(并使用 IDisposable 的 StreamWriter 对象)时,建议使用“Using”指令。一旦代码执行完成,这将关闭资源。

 using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }   

一旦你写了第三行,文件将自动关闭并释放资源。

于 2012-10-26T16:28:36.980 回答