是否有一个内置的方式来处理多个文件作为一个流? [英] Is there a built-in way to handle multiple files as one stream?

查看:163
本文介绍了是否有一个内置的方式来处理多个文件作为一个流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件列表,而我需要阅读给定大小的他们在每一个特定的顺序为字节[]。这本身不是一个单一的文件有问题,一个简单的而((有= fs.Read(片,0,pieceLength))> 0)的能够完成完全正常工作。最后一块文件可能会比预期的,这是罚款较小。

I have a list of files, and i need to read them each in a specific order into byte[] of a given size. This in itself is not a problem for a single file, a simple while ((got = fs.Read(piece, 0, pieceLength)) > 0) gets the job done perfectly fine. The last piece of the file may be smaller than desired, which is fine.

现在,还有一个棘手的一点:如果我有多个文件,我需要有一个连续流,这意味着,如果最后一块的文件更小的pieceLength,那么我需要阅读(pieceLength-GOT)下一个文件,然后一直下去,直到最后一个文件的末尾。

Now, there is a tricky bit: If I have multiple files, I need to have one continous stream, which means that if the last piece of a file is smaller that pieceLength, then I need to read (pieceLength-got) of the next file, and then keep on going on until the end of the last file.

所以基本上,给定的X文件,我会一直读到正是pieceLength长,除了最后一段的最后文件,这可能是较小的。

So essentially, given X files, I will always read pieces that are exactly pieceLength long, except for the very last piece of the very last file, which may be smaller.

我不知道是否已经有一些建立在.NET(3.5 SP1),做的伎俩。我目前的做法是创建一个类,它的文件列表,然后暴露了一个读(byte []的缓冲区,长期指标,长长度)的功能,类似的FileStream。读()。这应该是pretty的直线前进,因为我没有改变我的呼唤code,读取数据,但在此之前我推倒重来我只是想仔细检查车轮尚未建成的BCL。

I just wonder if there is already something build in .net (3.5 SP1) that does the trick. My current approach is to create a Class that takes a list of files and then exposes a Read(byte[] buffer, long index, long length) function, similar to FileStream.Read(). This should be pretty straight forward because I do not have to change my calling code that reads the data, but before I reinvent the wheel I'd just like to double check that the wheel is not already built into the BCL.

感谢:)

推荐答案

我不相信有一个在框架内什么,但我会建议使它多一点灵活的 - 采取的IEnumerable<流> 在构造函数,并从中自己。然后让文件流,你可以(假设C#3.0)只是做:

I don't believe there's anything in the framework, but I'd suggest making it a bit more flexible - take an IEnumerable<Stream> in your constructor, and derive from Stream yourself. Then to get file streams you can (assuming C# 3.0) just do:

Stream combined = new CombinationStream(files.Select(file => File.Open(file));

在所有权部分稍微棘手这里 - 上面将允许组合流,把它从读取任何数据流的所有权,但你的可以的不希望它有遍历所有其余的流,并关闭所有这些如果的的收prematurely。

The "ownership" part is slightly tricky here - the above would allow the combination stream to take ownership of any stream it reads from, but you may not want it to have to iterate through all the rest of the streams and close them all if it's closed prematurely.

这篇关于是否有一个内置的方式来处理多个文件作为一个流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆