在 .NET 中执行 stream.CopyTo(anotherStream) 时如何获得复制百分比?
How to get a copy-percent when doing a stream.CopyTo(anotherStream) in .NET?
我有两个流,我希望将内容从一个流复制到另一个流。
例如。 await stream1.CopyToAsync(stream2);
有没有一种方法可以连接到一个事件中,以便对于每.. 说.. 10K 字节的复制,我报告一些东西.. 或者每复制 1% 或什么.. 我就会触发一个事件?
查看 some examples,他们都建议我不要使用 CopyTo / CopyToAsync
方法,而是恢复到手动从 stream
复制数据的经典方法 => stream2
手动,固定数组。
您必须编写自己的方法,也许作为扩展方法。它可能看起来像这样:
public static async Task CopyToWithProgressAsync(this Stream source,
Stream destination,
int bufferSize = 4096,
Action<long> progress = null)
{
var buffer = new byte[bufferSize];
var total = 0L;
int amtRead;
do
{
amtRead = 0;
while(amtRead < bufferSize)
{
var numBytes = await source.ReadAsync(buffer,
amtRead,
bufferSize - amtRead);
if(numBytes == 0)
{
break;
}
amtRead += numBytes;
}
total += amtRead;
await destination.WriteAsync(buffer, 0, amtRead);
if(progress != null)
{
progress(total);
}
} while( amtRead == bufferSize );
}
你会这样称呼它:
stream1.CopyToWithProgressAsync(stream2,
4096,
amtCopied => Console.WriteLine(amtCopied))
我有两个流,我希望将内容从一个流复制到另一个流。
例如。 await stream1.CopyToAsync(stream2);
有没有一种方法可以连接到一个事件中,以便对于每.. 说.. 10K 字节的复制,我报告一些东西.. 或者每复制 1% 或什么.. 我就会触发一个事件?
查看 some examples,他们都建议我不要使用 CopyTo / CopyToAsync
方法,而是恢复到手动从 stream
复制数据的经典方法 => stream2
手动,固定数组。
您必须编写自己的方法,也许作为扩展方法。它可能看起来像这样:
public static async Task CopyToWithProgressAsync(this Stream source,
Stream destination,
int bufferSize = 4096,
Action<long> progress = null)
{
var buffer = new byte[bufferSize];
var total = 0L;
int amtRead;
do
{
amtRead = 0;
while(amtRead < bufferSize)
{
var numBytes = await source.ReadAsync(buffer,
amtRead,
bufferSize - amtRead);
if(numBytes == 0)
{
break;
}
amtRead += numBytes;
}
total += amtRead;
await destination.WriteAsync(buffer, 0, amtRead);
if(progress != null)
{
progress(total);
}
} while( amtRead == bufferSize );
}
你会这样称呼它:
stream1.CopyToWithProgressAsync(stream2,
4096,
amtCopied => Console.WriteLine(amtCopied))