Search code examples
c#memorystream

Multiple files in one MemoryStream?


Is it possible to save a list of files into one MemoryStream and save the files later back to the disc?


Solution

  • Well yeah, there are a few ways of doing this but one would be to do something like this:

    class MyFile
    {
        public byte[] Data;
        public string FileName;
    }
    
    List<MyFile> files = GetFiles();
    using (MemoryStream stream = new MemoryStream())
    {
        // Serialise
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, files);
    
        // Deserailise
        stream.Position = 0;
        List<MyFile> deserialisedFiles = (List<MyFile>)formatter.Deserialize(stream);
        SaveFiles(deserialisedFiles);
    }
    

    Where you should be able to figure out roughly the implementation of SaveFiles and GetFiles. I'm not entirely clear why you want to do this though.