Multiple stream in one stream will not passed to client properly

こ雲淡風輕ζ 提交于 2019-11-29 13:08:37

Wooow, Finally I get success to implement our scenario properly, going to put the answer here maybe someone wants to use the solution to returns multiple files in one stream.

there are several sample to return multiple files but all of them are returning byte array, I prefer to return stream because of many reason, the important thing is streams will perform better for large files since not all of it needs to be read into memory at one time and backward compatibility for my case.

So at the first step I have created a serializable DataContract to hold the name of file and it's content byte.

[DataContract]
[Serializable]
public class ExportSourceFiles_C
{
    [DataMember]
    public string Name;
    [DataMember]
    public byte[] Content;
}

at the second step a list of ExportSourceFile_C will be created like:

List<ExportSourceFiles_C> sourceFiles = new List<ExportSourceFiles_C>();
string[] zipFiles = Directory.GetFiles(zipRoot);
foreach (string path in zipFiles)
  {
     byte[] fileBytes = File.ReadAllBytes(path);
     sourceFiles.Add(new ExportSourceFiles_C()
     {
         Name = Path.GetFileName(path),
         Content = fileBytes
     });
  }

at the third step the mentioned list should be serialized to result.Stream like:

  result.Stream = new MemoryStream();
  BinaryFormatter formatter = new BinaryFormatter();
  formatter.Serialize(result.Stream, sourceFiles);
  result.Stream.Position = 0;
  return result;

in client side this is enough deserialize the stream to list of ExportSourceFiles_C so the last step in client side should be something like this:

 ExportClient export = new ExportClient("exportEndPoint");
 ExportResult_C result = export.Export(source);
 BinaryFormatter formatter = new BinaryFormatter();
 List<ExportSourceFiles_C> deserialisedFiles = (List<ExportSourceFiles_C>)formatter.Deserialize(result.Stream);
 foreach (ExportSourceFiles_C file in deserialisedFiles)
      File.WriteAllBytes("d:\\" + file.Name, file.Content);

everything works like a charm without any problem.

enjoy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!