C# 如何合并两个内存流?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15655210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to merge two memory streams?
提问by SaneDeveloper
I have two MemoryStream instances.
我有两个 MemoryStream 实例。
How to merge them into one instance?
如何将它们合并为一个实例?
Well, now I can't copy from one MemoryStream to another. Here is a method:
好吧,现在我无法从一个 MemoryStream 复制到另一个。这是一个方法:
public static Stream ZipFiles(IEnumerable<FileToZip> filesToZip) {
ZipStorer storer = null;
MemoryStream result = null;
try {
MemoryStream memory = new MemoryStream(1024);
storer = ZipStorer.Create(memory, GetDateTimeInRuFormat());
foreach (var currentFilePath in filesToZip) {
string fileName = Path.GetFileName(currentFilePath.FullPath);
storer.AddFile(ZipStorer.Compression.Deflate, currentFilePath.FullPath, fileName,
GetDateTimeInRuFormat());
}
result = new MemoryStream((int) storer.ZipFileStream.Length);
storer.ZipFileStream.CopyTo(result); //Does not work!
//result's length will be zero
}
catch (Exception) {
}
finally {
if (storer != null)
storer.Close();
}
return result;
}
采纳答案by illegal-immigrant
Spectacularly easy with CopyToor CopyToAsync:
使用CopyTo或CopyToAsync非常简单:
var streamOne = new MemoryStream();
FillThisStreamUp(streamOne);
var streamTwo = new MemoryStream();
DoSomethingToThisStreamLol(streamTwo);
streamTwo.CopyTo(streamOne); // streamOne holds the contents of both
The framework, people. The framework.
框架,人。该框架。
回答by illegal-immigrant
Create third(let it be
mergedStream
)MemoryStream
with length equal to sum of first and second lengthsWrite first
MemoryStream
tomergedStream
(useGetBuffer()
to getbyte[]
fromMemoryStream
)Write second
MemoryStream
tomergedStream
(useGetBuffer()
)Remember about offset while writing.
创建第三个(让它成为
mergedStream
)MemoryStream
,其长度等于第一个和第二个长度的总和先写
MemoryStream
到mergedStream
(使用GetBuffer()
获得byte[]
从MemoryStream
)写第二个
MemoryStream
到mergedStream
(使用GetBuffer()
)在写作时记住偏移量。
It's rather append, but it's totally unclear what is merge operation on MemoryStreams
它是append,但完全不清楚 MemoryStreams 上的合并操作是什么
回答by Amit
Based on the answer shared by @Will above, here is complete code:
根据上面@Will 分享的答案,这里是完整的代码:
void Main()
{
var s1 = GetStreamFromString("Hello");
var s2 = GetStreamFromString(" World");
var s3 = s1.Append(s2);
Console.WriteLine(Encoding.UTF8.GetString((s3 as MemoryStream).ToArray()));
}
public static Stream GetStreamFromString(string text)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
public static class Extensions
{
public static Stream Append(this Stream destination, Stream source)
{
destination.Position = destination.Length;
source.CopyTo(destination);
return destination;
}
}
And merging stream collection with async
:
并将流集合与async
:
async Task Main()
{
var list = new List<Task<Stream>> { GetStreamFromStringAsync("Hello"), GetStreamFromStringAsync(" World") };
Stream stream = await list
.Select(async item => await item)
.Aggregate((current, next) => Task.FromResult(current.Result.Append(next.Result)));
Console.WriteLine(Encoding.UTF8.GetString((stream as MemoryStream).ToArray()));
}
public static Task<Stream> GetStreamFromStringAsync(string text)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return Task.FromResult(stream as Stream);
}
public static class Extensions
{
public static Stream Append(this Stream destination, Stream source)
{
destination.Position = destination.Length;
source.CopyTo(destination);
return destination;
}
}