本文整理汇总了C#中System.IO.MemoryStream.Write方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.Write方法的具体用法?C# MemoryStream.Write怎么用?C# MemoryStream.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetImageDict
/// <summary>
/// Gets the image entries to be written to the file
/// </summary>
/// <returns></returns>
public byte[] GetImageDict(long filePos,out int size)
{
MemoryStream ms=new MemoryStream();
int s;
byte[] ba;
foreach (PdfImageEntry ie in images.Values)
{
ObjectList objList=new ObjectList(ie.objectNum,filePos);
ba = PdfUtility.GetUTF8Bytes(ie.imgDict, out s);
ms.Write(ba, 0, ba.Length);
filePos += s;
ms.Write(ie.ba, 0, ie.ba.Length); // write out the image
filePos += ie.ba.Length;
ba = PdfUtility.GetUTF8Bytes("endstream\r\nendobj\r\n", out s);
ms.Write(ba, 0, ba.Length);
filePos += s;
ie.xref.offsets.Add(objList);
}
ba = ms.ToArray();
size = ba.Length;
return ba;
}
示例2: GenerateKeyDataFromNonces
public static AESKeyData GenerateKeyDataFromNonces(byte[] serverNonce, byte[] newNonce) {
using (SHA1 hash = new SHA1Managed()) {
var nonces = new byte[48];
newNonce.CopyTo(nonces, 0);
serverNonce.CopyTo(nonces, 32);
byte[] hash1 = hash.ComputeHash(nonces);
serverNonce.CopyTo(nonces, 0);
newNonce.CopyTo(nonces, 16);
byte[] hash2 = hash.ComputeHash(nonces);
nonces = new byte[64];
newNonce.CopyTo(nonces, 0);
newNonce.CopyTo(nonces, 32);
byte[] hash3 = hash.ComputeHash(nonces);
using (var keyBuffer = new MemoryStream(32))
using (var ivBuffer = new MemoryStream(32)) {
keyBuffer.Write(hash1, 0, hash1.Length);
keyBuffer.Write(hash2, 0, 12);
ivBuffer.Write(hash2, 12, 8);
ivBuffer.Write(hash3, 0, hash3.Length);
ivBuffer.Write(newNonce, 0, 4);
return new AESKeyData(keyBuffer.ToArray(), ivBuffer.ToArray());
}
}
}
示例3: UrlEncodeAndWrite
// RFC: http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
private void UrlEncodeAndWrite(string value, MemoryStream memoryStream)
{
foreach (char symbol in value)
{
if (unreservedChars.IndexOf(symbol) != -1)
{
memoryStream.WriteByte((byte)symbol);
}
else if (symbol == ' ')
{
memoryStream.WriteByte(plus);
}
else if (symbol < 255)
{
var encodedValue = Encoding.ASCII.GetBytes(String.Format("%{0:X2}", (byte)symbol));
memoryStream.Write(encodedValue, 0, encodedValue.Length);
}
else
{
var bytes = Encoding.UTF8.GetBytes(new[] { symbol });
foreach (var @byte in bytes)
{
var encodedValue = Encoding.ASCII.GetBytes(String.Format("%{0:X2}", @byte));
memoryStream.Write(encodedValue, 0, encodedValue.Length);
}
}
}
}
示例4: GetPostDataWithMultipart
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public byte[] GetPostDataWithMultipart(string boundary)
{
var ms = new MemoryStream();
foreach (var p in Params)
{
if (p.Type == PostDataParamType.File)
{
var header = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\";\r\nContent-Type: application/octet-stream\r\n\r\n",
boundary,
p.FilePath);
ms.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));
ms.Write((byte[])p.Value, 0, ((byte[])p.Value).Length);
}
else
{
var postData = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
p.Name,
p.Value);
ms.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
var footer = "\r\n--" + boundary + "--\r\n";
ms.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
ms.Position = 0;
var tempBuffer = new byte[ms.Length];
ms.Read(tempBuffer, 0, tempBuffer.Length);
ms.Close();
return tempBuffer;
}
示例5: With_WebSocket_CanReadTwoBufferedSmallFrames
public void With_WebSocket_CanReadTwoBufferedSmallFrames()
{
var handshake = GenerateSimpleHandshake();
using (var ms = new MemoryStream())
using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions))
{
ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
var reader = ws.ReadMessageAsync(CancellationToken.None).Result;
Assert.IsNotNull(reader);
using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
{
String s = sr.ReadToEnd();
Assert.AreEqual("Hi", s);
}
reader = ws.ReadMessageAsync(CancellationToken.None).Result;
Assert.IsNotNull(reader);
using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
{
String s = sr.ReadToEndAsync().Result;
Assert.AreEqual("Hi", s);
}
reader = ws.ReadMessageAsync(CancellationToken.None).Result;
Assert.IsNull(reader);
}
}
示例6: EncryptStringAES
/// <summary>
/// AES加密
/// </summary>
/// <param name="plainText">要加密的字串</param>
/// <returns>加密后的字串</returns>
public static string EncryptStringAES(string plainText)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
string outStr = null;
RijndaelManaged aesAlg = null;
try
{
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _salt);
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
if (aesAlg != null)
aesAlg.Clear();
}
return outStr;
}
示例7: TestReadContinued
public void TestReadContinued()
{
//simulate a continues Drawing record
MemoryStream out1 = new MemoryStream();
//main part
DrawingRecord dg = new DrawingRecord();
byte[] data1 = new byte[8224];
Arrays.Fill(data1, (byte)1);
dg.Data = (/*setter*/data1);
byte[] dataX = dg.Serialize();
out1.Write(dataX, 0, dataX.Length);
//continued part
byte[] data2 = new byte[4048];
Arrays.Fill(data2, (byte)2);
ContinueRecord cn = new ContinueRecord(data2);
dataX = cn.Serialize();
out1.Write(dataX, 0, dataX.Length);
List<Record> rec = RecordFactory.CreateRecords(new MemoryStream(out1.ToArray()));
Assert.AreEqual(2, rec.Count);
Assert.IsTrue(rec[0] is DrawingRecord);
Assert.IsTrue(rec[1] is ContinueRecord);
Assert.IsTrue(Arrays.Equals(data1, ((DrawingRecord)rec[0]).Data));
Assert.IsTrue(Arrays.Equals(data2, ((ContinueRecord)rec[1]).Data));
}
示例8: Protect
public static byte[] Protect(byte[] encryptionKey, byte[] validationKey, byte[] initializationVector, byte[] plainText)
{
using (var provider = new AesCryptoServiceProvider())
{
using (ICryptoTransform transform = provider.CreateEncryptor(encryptionKey, initializationVector))
{
using (var ms = new MemoryStream())
{
ms.Write(initializationVector, 0, initializationVector.Length);
using (var cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
// Encrypted payload
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
// Compute signature
using (var sha = new HMACSHA256(validationKey))
{
checked
{
byte[] signature = sha.ComputeHash(ms.GetBuffer(), 0, (int)ms.Length);
// Write the signature to the paylod
ms.Write(signature, 0, signature.Length);
// Final bytes
return ms.ToArray();
}
}
}
}
}
}
}
示例9: Encode
public MemoryStream Encode(MemoryStream memoryStream)
{
memoryStream.Position = 0;
byte[] buffer320 = new byte[320];
byte[] buffer32 = new byte[32];
MemoryStream raw2armData = new MemoryStream();
raw2armData.Write(Encoding.UTF8.GetBytes("#!AMR\n"), 0, 6);
AMR_Encoder enc = new AMR_Encoder();
int start = 0;
int end = Convert.ToInt32(memoryStream.Length);
memoryStream.Position = start;
while (true)
{
if (end - start < 320)
{
memoryStream.Read(buffer320, 0, end - start);
for (int i = end - start; i < 320; i++)
{
buffer320[i] = 0;
}
}
else
{
memoryStream.Read(buffer320, 0, 320);
}
enc.Encode(buffer320, 0, buffer32, 0);
raw2armData.Write(buffer32, 0, buffer32.Length);
start += 320;
if (start >= end) break;
}
return raw2armData;
}
示例10: Encrypt
public static byte[] Encrypt(byte[] payload, CryptoContext cryptoContext)
{
var csEncrypt = cryptoContext.CryptoStreamOut;
var output = cryptoContext.OutputStream;
output.Position = 0;
output.SetLength(0);
using (MemoryStream hashStream = new MemoryStream())
{
// hash
SHA256Managed crypt = new SHA256Managed();
hashStream.Write(BitConverter.GetBytes(Interlocked.Increment(ref cryptoContext.SendCounter)), 0, 8);
hashStream.Write(payload, 0, payload.Length);
hashStream.Write(cryptoContext.Algorithm.Key, 0, cryptoContext.Algorithm.Key.Length);
var hashBuffer = hashStream.ToArray();
byte[] validationCheckSum = crypt.ComputeHash(hashBuffer, 0, hashBuffer.Length);
byte[] content = payload.Concat(validationCheckSum.Take(8)).ToArray();
csEncrypt.Write(content, 0, content.Length);
csEncrypt.Flush();
}
return output.ToArray();
}
示例11: DecodeFromHex
public static byte[] DecodeFromHex(byte[] inputBytes, bool bUseSpaces)
{
FromHexTransform hexTransform = new FromHexTransform();
byte[] outputBytes = new byte[hexTransform.OutputBlockSize];
MemoryStream outputStream = new MemoryStream();
int i = 0;
while (inputBytes.Length - i > hexTransform.InputBlockSize)
{
hexTransform.TransformBlock(inputBytes, i, hexTransform.InputBlockSize, outputBytes, 0);
i += hexTransform.InputBlockSize;
if (bUseSpaces)
{
i++;
}
outputStream.Write(outputBytes, 0, hexTransform.OutputBlockSize);
}
outputBytes = hexTransform.TransformFinalBlock(inputBytes, i, inputBytes.Length - i);
outputStream.Write(outputBytes, 0, outputBytes.Length);
//string strRet = System.Text.Encoding.UTF8.GetString(outputStream.ToArray());
byte[] arRet = outputStream.ToArray();
outputStream.Close();
return arRet;
}
示例12: Decrypt
public static Stream Decrypt(Stream source,
Headers headers, byte[] masterKey)
{
byte[] easKey;
using (var buffer = new MemoryStream())
{
var masterSeed = headers.MasterSeed;
buffer.Write(masterSeed, 0, masterSeed.Length);
buffer.Write(masterKey, 0, masterKey.Length);
easKey = BufferEx.GetHash(buffer.ToArray());
}
var eas = new AesManaged
{
KeySize = 256,
Key = BufferEx.Clone(easKey),
IV = BufferEx.Clone(headers.EncryptionIV)
};
Stream stream = new CryptoStream(source,
eas.CreateDecryptor(),
CryptoStreamMode.Read);
if (!VerifyStartBytes(headers, stream))
return null;
stream = new HashedBlockStream(stream, true);
return headers.Compression == Compressions.GZip
? new GZipInputStream(stream) : stream;
}
示例13: GetBytes
public override byte[] GetBytes(ID3v2TagVersion tagVersion)
{
// TODO: Test
if (string.IsNullOrEmpty(Text))
return new byte[0];
byte[] contentDescriptorData;
byte[] textData;
do
{
contentDescriptorData = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, ContentDescriptor, true);
textData = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, Text, false);
} while (
this.RequiresFix(tagVersion, ContentDescriptor, contentDescriptorData) ||
this.RequiresFix(tagVersion, Text, textData)
);
using (MemoryStream frameData = new MemoryStream())
{
frameData.WriteByte((byte)TextEncoding);
frameData.Write(ByteUtils.ISO88591GetBytes(LanguageCode));
frameData.Write(contentDescriptorData);
frameData.Write(textData);
return _frameHeader.GetBytes(frameData, tagVersion, GetFrameID(tagVersion));
}
}
示例14: WriteTransactionMessageBuffer
/// <summary>
/// Generates a buffer in which it puts the lenght of transaction's propagation token,
/// the propagation token, and lastly the message bytes. If the transaction propagation token
/// is null, we insert 4 null bytes at the beginning of the buffer.
/// </summary>
public static byte[] WriteTransactionMessageBuffer(byte[] txPropToken, ArraySegment<Byte> message)
{
// start writing all the info into a memory buffer
MemoryStream mem = new MemoryStream();
// copy the bytes encoding the length of the txPropToken
// first get the bytes representing the length of the txPropToken
byte[] txLengthBytes;
if (txPropToken != null)
{
txLengthBytes = BitConverter.GetBytes(txPropToken.Length);
}
else
{
txLengthBytes = BitConverter.GetBytes((int)0);
}
mem.Write(txLengthBytes, 0, txLengthBytes.Length);
// copy the bytes of the transaction propagation token
if (txPropToken != null)
{
mem.Write(txPropToken, 0, txPropToken.Length);
}
// copy the message bytes
mem.Write(message.Array, message.Offset, message.Count);
return mem.ToArray();
}
示例15: GetMultipartFormData
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
using (Stream formDataStream = new MemoryStream())
{
foreach (var param in postParameters)
if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", boundary, param.Key, fileToUpload.FileName ?? param.Key, fileToUpload.ContentType ?? "application/octet-stream");
formDataStream.Write(_encoding.GetBytes(header), 0, header.Length);
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
// Thanks to feedback from commenters, add a CRLF to allow multiple files to be uploaded
//formDataStream.Write(encoding.GetBytes("\r\n"), 0, 2);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key, param.Value);
formDataStream.Write(_encoding.GetBytes(postData), 0, postData.Length);
}
// Add the end of the request
string footer = String.Format("\r\n--{0}--\r\n", boundary);
formDataStream.Write(_encoding.GetBytes(footer), 0, footer.Length);
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
}