本文整理汇总了C#中System.IO.MemoryStream.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.ToArray方法的具体用法?C# MemoryStream.ToArray怎么用?C# MemoryStream.ToArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Encrypt
public byte[] Encrypt(byte[] block)
{
ICryptoTransform enc = null;
Aes.Mode = CipherMode.CBC;
Aes.Key = key;
Aes.GenerateIV();
Console.WriteLine("Key: {0} IV: {1}", CNetwork.ByteArrayToString(Aes.Key), CNetwork.ByteArrayToString(Aes.IV));
CryptoStream cstream = null;
MemoryStream mem = null;
byte[] toEncrypt = null;
try
{
cstream = null;
mem = new MemoryStream();
toEncrypt = block;
enc = Aes.CreateEncryptor();
cstream = new CryptoStream(mem, enc, CryptoStreamMode.Write);
cstream.Write(toEncrypt, 0, toEncrypt.Length);
}
finally
{
if (cstream != null)
Aes.Clear();
cstream.Close();
}
Console.WriteLine(CNetwork.ByteArrayToString(mem.ToArray()));
return mem.ToArray();
}
示例2: GetEncoding
public override byte[] GetEncoding()
{
try
{
MemoryStream outputStream = new MemoryStream();
BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));
MessagesEncodingUtil.WriteMessageType(binaryWriter, this);
if (PeerAddress.PrivateEndPoint == null)
MessagesEncodingUtil.WriteString(binaryWriter, "null");
else
MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PrivateEndPoint.ToString());
if (PeerAddress.PublicEndPoint == null)
MessagesEncodingUtil.WriteString(binaryWriter, "null");
else
MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PublicEndPoint.ToString());
binaryWriter.Flush();
byte[] buffer = outputStream.ToArray();
if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
return outputStream.ToArray();
else
throw new BinaryEncodingException();
}
catch (Exception)
{
throw new BinaryEncodingException("Decode");
}
}
示例3: Serialize
/// <summary>
/// Serializes this <see cref="Token"/> instance as a string that can be
/// included as part of a return_to variable in a querystring.
/// This string is cryptographically signed to protect against tampering.
/// </summary>
public string Serialize(INonceStore store) {
using (MemoryStream dataStream = new MemoryStream()) {
if (!persistSignature(store)) {
Debug.Assert(!persistNonce(Endpoint, store), "Without a signature, a nonce is meaningless.");
dataStream.WriteByte(0); // there will be NO signature.
StreamWriter writer = new StreamWriter(dataStream);
Endpoint.Serialize(writer);
writer.Flush();
return Convert.ToBase64String(dataStream.ToArray());
} else {
using (HashAlgorithm shaHash = createHashAlgorithm(store))
using (CryptoStream shaStream = new CryptoStream(dataStream, shaHash, CryptoStreamMode.Write)) {
StreamWriter writer = new StreamWriter(shaStream);
Endpoint.Serialize(writer);
if (persistNonce(Endpoint, store))
writer.WriteLine(Nonce.Code);
writer.Flush();
shaStream.Flush();
shaStream.FlushFinalBlock();
byte[] hash = shaHash.Hash;
byte[] data = new byte[1 + hash.Length + dataStream.Length];
data[0] = 1; // there is a signature
Buffer.BlockCopy(hash, 0, data, 1, hash.Length);
Buffer.BlockCopy(dataStream.ToArray(), 0, data, 1 + hash.Length, (int)dataStream.Length);
return Convert.ToBase64String(data);
}
}
}
}
示例4: ImageFromLogo
/// <summary>
/// Convert the Webstreamlogo (Online or Default) to byte[]
/// </summary>
public static byte[] ImageFromLogo(string path)
{
var ms = new MemoryStream();
try
{
var imageRequest = (HttpWebRequest)WebRequest.Create(path);
imageRequest.Credentials = CredentialCache.DefaultCredentials;
using (var imageReponse = (HttpWebResponse)imageRequest.GetResponse())
{
using (var imageStream = imageReponse.GetResponseStream())
{
if (imageStream != null) Image.FromStream(imageStream).Save(ms, ImageFormat.Png);
}
}
}
catch (Exception)
{
var s = ServiceRegistration.Get<IPathManager>().GetPath(@"<PLUGINS>\Webradio\Skin\default\images\DefaultLogo.png");
Image.FromFile(s).Save(ms, ImageFormat.Png);
return ms.ToArray();
throw;
}
return ms.ToArray();
}
示例5: Run
public void Run()
{
var registerer = new MessageRegisterer();
registerer.AddMessageTypes(typeof(IPerformSingleTaskOnComputersMessage), typeof(IInstallAssemblyMessage));
var implementations = new MessageInterfaceImplementations(new DefaultMessageInterfaceImplementationFactory(), registerer);
var factory = new MessageFactory(implementations, new MessageDefinitionFactory());
var assembly = factory.Create<IInstallAssemblyMessage>(m =>
{
m.ArtifactId = Guid.Empty;
m.AssemblyFilename = "Jacob.exe";
});
var message = factory.Create<IPerformSingleTaskOnComputersMessage>(m =>
{
m.OperationId = Guid.NewGuid();
m.Title = "Nothing";
m.Message = assembly;
m.ComputerNames = new string[0];
m.Birthday = DateTime.UtcNow;
});
var formatter = new XmlTransportMessageBodyFormatter(registerer, new MtaMessageMapper(implementations, factory, registerer));
formatter.Initialize();
using (var stream = new MemoryStream())
{
formatter.Serialize(new IMessage[] { message }, stream);
Console.WriteLine(Encoding.ASCII.GetString(stream.ToArray()));
using (var reading = new MemoryStream(stream.ToArray()))
{
var read = formatter.Deserialize(reading);
}
}
}
示例6: SendServerInfo
/// <summary>
/// Send information about this CityServer to the LoginServer...
/// </summary>
/// <param name="Client">The client connected to the LoginServer.</param>
public static void SendServerInfo(NetworkClient Client)
{
PacketStream Packet = new PacketStream(0x64, 0);
Packet.WriteByte(0x64);
MemoryStream PacketBody = new MemoryStream();
BinaryWriter PacketWriter = new BinaryWriter(PacketBody);
PacketWriter.Write((string)GlobalSettings.Default.CityName);
PacketWriter.Write((string)GlobalSettings.Default.CityDescription);
PacketWriter.Write((string)Settings.BINDING.Address.ToString());
PacketWriter.Write((int)Settings.BINDING.Port);
PacketWriter.Write((byte)1); //CityInfoStatus.OK
PacketWriter.Write((ulong)GlobalSettings.Default.CityThumbnail);
PacketWriter.Write((string)GlobalSettings.Default.ServerID);
PacketWriter.Write((ulong)GlobalSettings.Default.Map);
PacketWriter.Flush();
Packet.WriteUInt16((ushort)(PacketBody.ToArray().Length + PacketHeaders.UNENCRYPTED));
Packet.Write(PacketBody.ToArray(), 0, (int)PacketWriter.BaseStream.Length);
Packet.Flush();
PacketWriter.Close();
Client.Send(Packet.ToArray());
}
示例7: GetEncoding
public override byte[] GetEncoding()
{
try
{
MemoryStream outputStream = new MemoryStream();
BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));
MessagesEncodingUtil.WriteMessageType(binaryWriter, this);
MessagesEncodingUtil.WriteInt(binaryWriter, ByteArray.Length);
MessagesEncodingUtil.WriteByteArray(binaryWriter, ByteArray);
binaryWriter.Flush();
byte[] buffer = outputStream.ToArray();
if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
return outputStream.ToArray();
else
throw new BinaryEncodingException();
}
catch (Exception)
{
throw new BinaryEncodingException("Decode");
}
}
示例8: NewToOld
public void NewToOld()
{
var oldMsg = new OldCacheUpdateRequest(new Uri("http://bob/phil"));
var oldold = Factory.ConvertToOldCacheUpdateRequest(oldMsg);
using (var newStream = new MemoryStream())
{
PlainFormatter.Serialize(newStream, oldold);
newStream.Position = 0;
using (var oldStream = new MemoryStream())
{
using (var str = File.OpenRead(_pathToFile))
{
var buff = new byte[str.Length];
str.Read(buff, 0, buff.Length);
oldStream.Write(buff, 0, buff.Length);
}
var newFileName = ".\\new-{0}.txt".FormatWith(oldMsg.GetType().Name);
if (File.Exists(newFileName)) File.Delete(newFileName);
using (var fs = File.OpenWrite(newFileName))
{
fs.Write(newStream.ToArray(), 0, newStream.ToArray().Length);
}
StreamAssert.AreEqual(oldStream, newStream);
}
}
}
示例9: VerifyAndSave
public static void VerifyAndSave(this Image image, string filename, Action<Stream> save = null)
{
var directory = Path.GetDirectoryName(filename);
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
var ms = new MemoryStream();
if (save != null)
save(ms);
else
image.SaveAsPng(ms);
if (File.Exists(filename))
{
try
{
Assert.Equal(ms.ToArray(), File.ReadAllBytes(filename));
}
catch
{
var actualName = Path.Combine(
Path.GetDirectoryName(filename),
$"{ Path.GetFileNameWithoutExtension(filename) }.actual{ Path.GetExtension(filename) }");
File.WriteAllBytes(actualName, ms.ToArray());
throw;
}
}
else
{
File.WriteAllBytes(filename, ms.ToArray());
}
}
示例10: MinimumBuffer
public static IObservable<byte[]> MinimumBuffer(this IObservable<byte[]> input, int minimumBufSize)
{
return Observable.Create<byte[]>(observer =>
{
MemoryStream memStream = new MemoryStream();
return input.Subscribe(
bytes =>
{
memStream.Write(bytes, 0, bytes.Length);
if (memStream.Length >= minimumBufSize)
{
Debug.Assert(memStream.Position == memStream.Length);
observer.OnNext(memStream.ToArray());
memStream.SetLength(0);// truncate the stream
memStream.Position = 0;
}
},
observer.OnError,
() =>
{
if (memStream.Length > 0)
observer.OnNext(memStream.ToArray());
observer.OnCompleted();
}
);
});
}
示例11: TestNil
public void TestNil()
{
var output = new MemoryStream();
Packer.Create( output ).PackNull();
Assert.AreEqual( null, Unpacking.UnpackNull( new MemoryStream( output.ToArray() ) ) );
Assert.AreEqual( null, Unpacking.UnpackNull( output.ToArray() ).Value );
}
示例12: nextToken
public static byte[] nextToken(Stream input, byte[] delimiter)
{
int nextByte;
//If the stream has already ended, return null
if ((nextByte = input.ReadByte()) == -1)
return null;
MemoryStream tokenBuffer = new MemoryStream();
do
{
tokenBuffer.WriteByte((byte)nextByte);
byte[] currentToken = tokenBuffer.ToArray();
if (endsWith(currentToken, delimiter))
{
int tokenLength = currentToken.Length - delimiter.Length;
byte[] token = new byte[tokenLength];
Array.Copy(currentToken, 0, token, 0, tokenLength);
return token;
}
}
while ((nextByte = input.ReadByte()) != -1);
return tokenBuffer.ToArray();
}
示例13: WriteQueryToStream
public override async Task WriteQueryToStream(Stream stream, ILogger logger, Spec.Query query, CancellationToken cancellationToken)
{
using (var memoryBuffer = new MemoryStream(1024))
using (var streamWriter = new StreamWriter(memoryBuffer, utf8Encoding))
{
WriteQuery(new JsonWriter(streamWriter), query);
streamWriter.Flush();
var data = memoryBuffer.ToArray();
memoryBuffer.Seek(0, SeekOrigin.Begin);
if (logger.InformationEnabled())
{
string dataStr = Encoding.UTF8.GetString(data);
logger.Information("JSON query: {0}", dataStr);
}
var tokenHeader = BitConverter.GetBytes(query.token);
if (!BitConverter.IsLittleEndian)
Array.Reverse(tokenHeader, 0, tokenHeader.Length);
memoryBuffer.Write(tokenHeader, 0, tokenHeader.Length);
var lengthHeader = BitConverter.GetBytes(data.Length);
if (!BitConverter.IsLittleEndian)
Array.Reverse(lengthHeader, 0, lengthHeader.Length);
memoryBuffer.Write(lengthHeader, 0, lengthHeader.Length);
memoryBuffer.Write(data, 0, data.Length);
logger.Debug("Writing packet, {0} bytes", data.Length);
data = memoryBuffer.ToArray();
await stream.WriteAsync(data, 0, data.Length, cancellationToken);
}
}
示例14: Download
public void Download(byte[] data, int bufferSize, DownloadSegmentPositions[] segmentPositionInfos)
{
BeforeDownload();
DownloadStream inputStream = new DownloadStream(data);
IList<ISegmentDownloadTask> segmentDownloadTasks = new List<ISegmentDownloadTask>(segmentPositionInfos.Length);
IList<DownloadStream> downloadStreams = new List<DownloadStream>(segmentPositionInfos.Length);
MemoryStream outputStream = new MemoryStream();
for (int i = 0; i < segmentPositionInfos.Length; i++)
{
DownloadSegmentPositions segmentPosition = segmentPositionInfos[i];
byte[] dataPart = data.Skip((int) segmentPosition.StartPosition).Take((int)(segmentPosition.EndPosition - segmentPosition.StartPosition + 1)).ToArray();
DownloadStream downloadStream = new DownloadStream(dataPart);
segmentDownloadTasks.Add(CreateSegmentDownloadTask(bufferSize, CreateSegmentDownloader(downloadStream, segmentPosition), CreateSegmentWriter(outputStream)));
downloadStreams.Add(downloadStream);
}
SegmentDownloadManager segmentDownloadManager = new SegmentDownloadManager(new SegmentDownloadTaskCollection(segmentDownloadTasks));
segmentDownloadManager.Start();
segmentDownloadManager.Finish(true);
AfterDownload();
long totalDownloads = downloadStreams.Sum(x => x.TotalDownloads);
Assert.AreEqual(data.Length, totalDownloads);
Assert.AreEqual(inputStream.ToArray().Take(data.Length).ToArray(), outputStream.ToArray().Take(data.Length).ToArray());
Assert.AreEqual(inputStream.ToArray(), outputStream.ToArray());
}
示例15: hashAndEncode
public static String hashAndEncode(byte[] password, int hashalg, byte[] salt, int icount, byte[] challenge)
{
byte[] hash;
if (hashalg == 0)
{
hash = sha1(password);
}
else
{
hash = HashPasswordV2(hashalg, salt, icount, password);
}
if (challenge.Length > 0)
{
var ms = new MemoryStream();
ms.Write(challenge, 0, challenge.Length);
ms.Write(hash, 0, hash.Length);
if (hashalg == 0)
hash = sha1(ms.ToArray());
else
{
hash = HashPasswordV2(hashalg, salt, icount, ms.ToArray());
}
}
return hexEncode(hash);
}