【问题标题】:How to split a Filestream into two substreams如何将文件流拆分为两个子流
【发布时间】:2017-08-23 17:37:00
【问题描述】:

有没有办法分割通过

获得的文件流
File.Open("100GB.bin", FileMode.Open, FileAccess.Read, FileShare.Read)

分成 2 个大小相同的子流? 我想将文件部分上传到网站,但网络服务器对允许发布的最大文件大小有限制。 需要两个流才能同时将部件上传到网站。 提前致谢。

【问题讨论】:

标签: c#


【解决方案1】:

如果网站不提供分段上传机制,只需将N个字节读入不同的流:

using (var fs = File.Open("100GB.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    var chunkSizeInBytes = ...; // whatever you like, below code assumes it's evenly divisible into your 100GB file
    var numChunks = fs.Length / chunkSizeInBytes;
    var buf = new byte[chunkSizeInBytes];
    for (int i = 0, bufIndex = 0; i < numChunks; ++i, bufIndex += chunkSizeInBytes) 
    {
        fs.Read(buf, bufIndex, chunkSizeInBytes);
        // if, for whatever reason, you actually need a new stream, 
        // just create a MemoryStream and use fs.CopyTo(stream, size)
        PostMyData(buf);
    }    
}

【讨论】:

  • Urrm 我忘了告诉你我想同时上传它们以减少上传所需的时间。出于这个原因,我需要 2 个或更多从根流派生的流。
  • @AllCowsAreBurgers:不,你没有;您只需要预先设置缓冲区偏移量并启动一些线程(任务)。据我所知,阅读是线程安全的。当然,您也可以创建多个流,只需创建它们、设置偏移量并使用CopyTo。向这里已经存在的代码添加并行性并不是一个很大的转变,想法是一样的。我认为没有必要在这里涉及复杂的流管理内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 2020-01-08
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多