c# – C # – Freeing a file


There are BinaryReader and BinaryWriter which write and read at the same time. There is a progressBar. When I close the application while working, I get an Exception in progressBar and using the delegate I do Close () & Dispose () BinaryReader, BinaryWriter and FileStream, which is used in BinaryReader. Nevertheless, the file is not released for some reason.

streamRead – FileStream; reader – BinaryReader;

using (streamRead = new FileStream(filePath, FileMode.Open))
            reader = new BinaryReader(streamRead);

writer – BinaryWriter

 using (writer = new BinaryWriter(File.Open(this.txbxArchivePath.Text + @"\" + this.txbxArchiveName.Text + ".Haffman", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))){ }

the method that I call using the delegate:

private void DisposeAll()




On MSDN they write :

"Do not interrupt the thread that is performing the read operation. Although the application may appear to execute successfully after the thread is not blocked, interruptions can degrade the performance and reliability of the application." most likely this is what was meant

Surely, it was meant that the execution of the Close() & Dispose() methods may not be executed correctly.

Try this example:

 class MyReader
    bool _breakReader = false;

    public void Close()
        _breakReader = true;

    public byte[] Read(string file)
        byte[] bytes;

            using (FileStream fsSource = new FileStream(file,
                FileMode.Open, FileAccess.Read))

                bytes = new byte[fsSource.Length];
                //Здесь можно указать нужный буфер 
                int numBytesToRead = 1024*1024; //1 МБ
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                    int n = fsSource.Read(bytes, 
                        numBytesRead, numBytesToRead);
                    // Здесь будет прерывание считывания
                    if (n == 0 || _breakReader )

                    numBytesRead += n;
                    numBytesToRead -= n;
                numBytesToRead = bytes.Length;
        catch (FileNotFoundException ioEx)
        return bytes;

As a result, it turns out that we read the file one megabyte at a time, if during reading the flag changed to true , then we interrupt the reading cycle and correctly close the FileStream

Scroll to Top