Leonid
Leonid

Reputation: 478

how to close all FileStreams related to specific file?

I got a file stream:

tempOutputStream = new FileStream(sTempFileName, FileMode.OpenOrCreate, 
    FileAccess.ReadWrite, FileShare.ReadWrite);

Once the file is created you can create additional FileStreams to read/write tempOutputStream. Is there a way to close all of them not having a ref to each stream obj? Or at least for the first one that creates the stream.

the problem is that I'd like to delete the file but one of the streams is not closed so I got an exception in File.Delete...

Thank you.

Regards, Leonid

Upvotes: 1

Views: 4647

Answers (2)

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19976

One possible solution:

  • extend the FileStream class, or create your Stream derivation
  • in it, add method something like GetNewStream()
  • that method can return new stream, and write its reference to some internal List<Stream>
  • override Close(), and Close() each stream from the list
  • override Dispose(), and Dispose() each stream from the list

That way you'll hide your functionality where it should be, away from you in the main line of code.

Another, to prevent hard refactoring:

  • my guess is that you have something like Stream s=originalStream.GetStream(); in your code (I don't know by heart how the stream is duplicated...)
  • create a singleton, that will contain Map<Stream, list<Stream>> and several methods:
    • RegisterStreamChild(Stream Parent, Stream Child);
    • CloseAllChildSteams(Stream Parent)
  • implement those methods using the Map<> contained in the singleton
  • search your code for occurrences of stream duplication. Use first method to register new stream
  • search your code for occurrences of stream closing. Use second method to close all child streams

Upvotes: 1

SLaks
SLaks

Reputation: 887867

No, there isn't.

You need to fix your code and ensure that all streams are closed when you finish using them.
Use the using statement.

Upvotes: 1

Related Questions