Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.
CopyTo() 是從 .NET Framework 4.0 才可以有的功能,來驗證看看
namespace StreamCopyTo
{
internal class Program
{
static void Main(string[] args)
{
using FileStream source = File.OpenRead(@"D:\Demo.txt");
Console.WriteLine($"Source length:{source.Length}");
Console.WriteLine($"Source Position:{source.Position}");
Console.WriteLine("");
Console.WriteLine("----- CASE 1 ------");
Console.WriteLine("");
using MemoryStream destination = new MemoryStream();
source.Position = 0;
Console.WriteLine($"source Start Position:{source.Position}");
source.CopyTo(destination);
Console.WriteLine($"Destination length:{destination.Length}");
Console.WriteLine($"Source - Destination Position:{source.Position}-{destination.Position}");
if (destination.Length == destination.Position)
Console.WriteLine("到達目的端檔案尾");
Console.WriteLine("");
Console.WriteLine("----- CASE 2 ------");
Console.WriteLine("");
using MemoryStream destination2 = new MemoryStream();
source.Position = 8933; // 單純為了湊整數而已,沒有意義
Console.WriteLine($"source Start Position:{source.Position}");
source.CopyTo(destination2);
Console.WriteLine($"Destination length:{destination2.Length}");
Console.WriteLine($"Source - Destination Position:{source.Position}-{destination2.Position}");
}
}
}