开发者

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 t开发者_如何转开发hat 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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜