MemoryStream 的使用

 

範例如下

using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Text;

namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
byte[] sourceTextByte = Encoding.UTF8.GetBytes(“ABC”);
MemoryStream memoryStream = new MemoryStream(sourceTextByte);
byte[] destinationTextByte = new byte[sourceTextByte.Length];
memoryStream.Read(destinationTextByte, 0, sourceTextByte.Length);
Console.WriteLine(Encoding.UTF8.GetString(destinationTextByte));
memoryStream.Close();
byte[] sourceTextByte2 = Encoding.UTF8.GetBytes(“ABCDE”);
MemoryStream memoryStream2 = new MemoryStream(sourceTextByte2);
byte[] destinationTextByte2 = new byte[sourceTextByte2.Length];
int index = 0;
int readLength = 3;
while (index < memoryStream2.Length)
{
long a = memoryStream2.Position;
if (index + readLength > memoryStream2.Length)
index += memoryStream2.Read(destinationTextByte2, index, (int)memoryStream2.Length - index);
else
index += memoryStream2.Read(destinationTextByte2, index, readLength);
}
Console.WriteLine(Encoding.UTF8.GetString(destinationTextByte2));
memoryStream2.Close();
}
}
}

說明:

重點在於 MemoryStream 的 Read 參數的用法,語法如下,

MemoryStream.Read(目的寫入,寫入位置,寫入量)