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");
            }   

3行目を書くと、ファイルは自動的に閉じられ、リソースが破棄されます。

于 2012-10-26T16:28:36.980 に答える