Creating a partial (or bounded) FileStream in C#
I have a FileStream that consists of several files put into one file, and I have a list of the lengths of the files, in other words I can easely calculate the position and length of all the files. What I want to create is a Open-method that takes a 开发者_如何学JAVAfileindex and returns a stream containing only that file. Currently I've implemented this using a memory-stream, but that forces me to copy the whole (not the container, but the whole contained) file into memory, and I don't want to do that. So, what I would like to be able to do is create a class that implements stream and takes another stream, a offset and a length parameter and then is readable and seekable, only when you do Seek(0) you should get to the offset of the underlaying stream. So like an adapter-class, and I was wondering if this was possible, or even a good idea, or if anyone has any better ideas of how to solve this problem. I realize that if I do it the way I just described I need to make sure that access to the underlaying stream is synchronized, and that all of the partial streams open holds a private variable telling them where currently in the stream they are, but this should probably be dooable, right? has anyone done anything like this before? Or is there a simpel .NET-class I can just use? Any help would be appreciated.
Oh, and sorry for bad english, I forgot to install my browser in english, so spellchecker tells me everything is wrong.
If you're using .NET 4.0, you could use memory-mapped files. They do pretty much what you've described: you can map a "view" of a large file, specified by an offset and a length, into memory, and access just that part of the file using a Stream
.
Otherwise, I think your approach sounds good. Just watch out for corner cases involving reading or writing beyond the boundaries of the intended file!
精彩评论