O
O
outrunningkarma2021-01-23 19:14:04
C++ / C#
outrunningkarma, 2021-01-23 19:14:04

System.ObjectDisposedException: "The closed file cannot be accessed." it's not clear what's wrong?

I decided to write a form that, when entered into a textBox, determines whether it is a leap year or not and writes the data to files. If the year is a leap year, then it is written to docx, if normal, then to txt. But it throws an error:

System.ObjectDisposedException
  HResult=0x80131622
  Сообщение = Доступ к закрытому файлу невозможен.
  Источник = mscorlib
  Трассировка стека:
   в System.IO.__Error.FileNotOpen()
   в System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
   в System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
   в System.IO.StreamWriter.Dispose(Boolean disposing)
   в System.IO.StreamWriter.Close()
   в Wfiles_years.Form1.button1_Click(Object sender, EventArgs e) в C:\Users\Alikhan\source\repos\Wfiles_years\Form1.cs:строка 58
   в System.Windows.Forms.Control.OnClick(EventArgs e)
   в System.Windows.Forms.Button.OnClick(EventArgs e)
   в System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   в System.Windows.Forms.Control.WndProc(Message& m)
   в System.Windows.Forms.ButtonBase.WndProc(Message& m)
   в System.Windows.Forms.Button.WndProc(Message& m)
   в System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   в System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   в System.Windows.Forms.Application.Run(Form mainForm)
   в Wfiles_years.Program.Main() в C:\Users\Alikhan\source\repos\Wfiles_years\Program.cs:строка 19

And here is the code itself:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Wfiles_years
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

      

        private void button1_Click(object sender, EventArgs e)
        {
            int year = Convert.ToInt32(textBox1.Text);

            FileStream fileV = new FileStream(@"C:\Users\Alikhan\Desktop\CSharp\yeardz\Year1.docx", FileMode.OpenOrCreate);
            FileStream fileO = new FileStream(@"C:\Users\Alikhan\Desktop\CSharp\yeardz\Year2.txt", FileMode.OpenOrCreate);
            StreamWriter writerV = new StreamWriter(fileV);
            StreamWriter writerO = new StreamWriter(fileO);

            if (year % 4 !=0)
            {
                writerO.WriteLine();
            }
            else if (year % 100 == 0)
            {
                if (year % 400 == 0)
                {
                    writerV.WriteLine();
                }
                else
                {
                    writerO.WriteLine();
                }
            }
            else
            {
                writerO.WriteLine();
            }





            fileV.Close();
            fileO.Close();
            writerV.Close();    // Ругается к этой функций.
            writerO.Close();


        }

        private void button2_Click(object sender, EventArgs e)
        {
            Directory.Delete(@"C:\Users\Alikhan\Desktop\CSharp\yeardz\Year1.docx");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Directory.Delete(@"C:\Users\Alikhan\Desktop\CSharp\yeardz\Year2.txt");
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2021-01-23
@outrunningkarma

According to the docs , the y method Closecloses StreamWriterthe underlying stream on its own (in your case, it's FileStream). And when closing the underlying stream, StreamWriterit tries to write to it everything that may have managed to accumulate in the buffer, but has not yet been written (line

System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
in your stacktrace).
But since the file stream is already closed, calling the method Flushresults in an error.
A tip for the future is to close streams in the reverse order you opened them. Those. if you opened them in order A -> B(A) -> C(B), then you should close them in order C, B, A.
At least in Java, closing an already closed stream is essentially a no-op (if the stream is already closed, it's done returnfrom within the Close). And I suspect that C# does the same. This means that there will be no such errors.

A
Alexander Ananiev, 2021-01-23
@SaNNy32

The message says

The closed file cannot be accessed.

You need to open the file for writing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question