【问题标题】:Multiple file in one Stream, custom stream一个流中的多个文件,自定义流
【发布时间】:2016-10-29 09:13:05
【问题描述】:

根据答案here我想将多个文件流写入一个流,如下所示:

为每个流的长度编号保留4个字节 每个流内容写在它的长度数字之后(4字节之后) 最后流将是这样的

流 = File1 len + File1 stream content + File2 len + File2 stream content + ....

示例代码:

result = new ExportResult_C()
            {
                PackedStudy = packed.ToArray() ,
                Stream = new MemoryStream()
            };
            string[] zipFiles = Directory.GetFiles(zipRoot);
            foreach (string fileN in zipFiles)
            {
                MemoryStream outFile = new MemoryStream(File.ReadAllBytes(fileN));
                MemoryStream len = new MemoryStream(4);
                //initiate outFile len to 4 byte push it to main stream
                //Then push outFile stream to main stream
                //Continue and do this for another file 
            } 
            //For test Save stream to file(s)

这是个好主意吗?真不知道这些 cmets 怎么可能是代码行。

提前致谢。

【问题讨论】:

  • 将数据打包到单个流中没有错。如果 Steam 包含多种类型,您可能还想在字节计数之后/之前添加一个单字节消息类型。
  • 感谢您的评论,并非所有文件都只有一种类型(zip),但是如何?

标签: c# .net stream


【解决方案1】:

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] testMessage = Encoding.UTF8.GetBytes("The quick brown fox jumped over the lazy dog");
            MemoryStream outFile = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(outFile);
            for (int i = 0; i < 10; i++ )
            {
                writer.Write(BitConverter.GetBytes(testMessage.Length), 0, 4);
                writer.Write(testMessage, 0, testMessage.Length);
            }
            writer.Flush();

            outFile.Position = 0;
            BinaryReader reader = new BinaryReader(outFile, Encoding.UTF8);
            while (outFile.Position < outFile.Length)
            {
                int size = reader.ReadInt32();
                byte[] data = reader.ReadBytes(size);
            }
        }
    }
}

【讨论】:

  • 没什么不同,那只是变量名,所以outFile 将是所有文件的流?
  • 在消费者端应该如何阅读,我应该使用BinaryReader吗?
  • 谢谢,但什么也没发生,我已将outFile 作为流传递。
  • 检查流的位置和长度以确保有数据。还有助于刷新 writer 以确保推送所有数据。
【解决方案2】:

我认为我发布了一个更好的解决方案来回答我的问题here 多个文件字节将被序列化为一个流,在客户端它将被反序列化为一类字节数组。

见here,它可能有用。

但我已接受@jdweng 解决方案,我感谢他的关注和帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多