在 C# 中创建部分(或有界)FileStream
我有一个 FileStream,它由放入一个文件的多个文件组成,并且我有一个文件长度的列表,换句话说,我可以轻松计算所有文件的位置和长度。我想要创建的是一个 Open 方法,它接受文件索引并返回仅包含该文件的流。目前我已经使用内存流实现了这一点,但这迫使我将整个(不是容器,而是整个包含的)文件复制到内存中,而我不想这样做。所以,我希望能够做的是创建一个实现流并接受另一个流、偏移量和长度参数的类,然后是可读和可查找的,只有当您执行 Seek(0) 时,您才应该获得偏移量的底层流。就像适配器类一样,我想知道这是否可能,甚至是一个好主意,或者是否有人对如何解决这个问题有更好的想法。我意识到,如果我按照我刚才描述的方式进行操作,我需要确保对底层流的访问是同步的,并且所有打开的部分流都拥有一个私有变量,告诉它们当前在流中的位置,但是这个应该是可行的,对吧?以前有人做过这样的事情吗?或者有一个简单的 .NET 类我可以使用吗?任何帮助将不胜感激。
哦,抱歉英语不好,我忘记用英语安装浏览器,所以拼写检查器告诉我一切都错了。
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 fileindex 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的是 .NET 4.0,则可以使用内存映射文件。它们的作用与您所描述的差不多:您可以将由偏移量和长度指定的大文件的“视图”映射到内存中,并使用
Stream
。否则,我认为你的方法听起来不错。只需注意涉及超出预期文件边界的读取或写入的极端情况!
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!