Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Multiple file in one Stream, custom stream

According to the answer here I want to write multiple files stream to one stream as following:

4 byte reserved for length number of each stream each stream content write after it's length number(after 4 byte) at the end stream will be something like this

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

Example code:

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)

is it good idea? really don't know how that comments can be lines of code.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

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);
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...