There are BinaryReader and BinaryWriter, which simultaneously write and read. There is a progressBar. When I close the application while I work, I get Exception in the progressBar and use the delegate to do Close () & Dispose () BinaryReader, BinaryWriter and FileStream, which is used in BinaryReader. Nevertheless, the file for some reason is not released.

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 with the delegate:

 private void DisposeAll() { this.reader.Close(); this.writer.Close(); streamRead.Close(); this.reader.Dispose(); this.writer.Dispose(); streamRead.Dispose(); this.Dispose(); } 
  • bring the text of the exception - Alex78191
  • System.IO.IOException: 'The process cannot access the file because the file is being used by another process.' - Sergey
  • one
    File.Open returns a FileStream . It must be saved in a separate variable (field) and also closed / disposed. - Alexander Petrov

1 answer 1

On MSDN they write :

"Do not interrupt the thread performing the read operation. Although the application may be displayed for successful execution after the thread is not blocked, the interruption may lead to a decrease in the performance and reliability of the application." most likely it was meant

Surely, this meant that the execution of the Close() & Dispose() methods may not be performed correctly.

Try this example:

  class MyReader { bool _breakReader = false; public void Close() { _breakReader = true; } public byte[] Read(string file) { byte[] bytes; try { 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 ) break; numBytesRead += n; numBytesToRead -= n; } numBytesToRead = bytes.Length; } } catch (FileNotFoundException ioEx) { Console.WriteLine(ioEx.Message); } return bytes; } } 

The result is that we read the file by one megabyte, if during the reading the flag has changed to true , then we interrupt the reading cycle and correctly close the FileStream

  • Why not a BufferedStream? - Sergey
  • @Sergey, I do not understand your question. If you need optimization - use buffers, do not need - you can not use. - Chloroform
  • I understood. I wanted to know if there are any reasons not to use the BufferedStream. Thanks for the answer! - Sergey