本文整理汇总了C#中MemoryStream.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.ToArray方法的具体用法?C# MemoryStream.ToArray怎么用?C# MemoryStream.ToArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestKnownEnc
static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
{
Byte[] CipherCalculated;
Console.WriteLine("Encrypting the following bytes:");
PrintByteArray(Plain);
Console.WriteLine("With the following Key:");
PrintByteArray(Key);
Console.WriteLine("and IV:");
PrintByteArray(IV);
Console.WriteLine("Expecting this ciphertext:");
PrintByteArray(Cipher);
ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
cs.Write(Plain,0,Plain.Length);
cs.FlushFinalBlock();
CipherCalculated = ms.ToArray();
cs.Close();
Console.WriteLine("Computed this cyphertext:");
PrintByteArray(CipherCalculated);
if (!Compare(Cipher, CipherCalculated)) {
Console.WriteLine("ERROR: result is different from the expected");
return false;
}
Console.WriteLine("OK");
return true;
}
示例2: RedirectedOutputDoesNotUseAnsiSequences
public static void RedirectedOutputDoesNotUseAnsiSequences()
{
// Make sure that redirecting to a memory stream causes Console not to write out the ANSI sequences
MemoryStream data = new MemoryStream();
TextWriter savedOut = Console.Out;
try
{
Console.SetOut(new StreamWriter(data, new UTF8Encoding(false), 0x1000, leaveOpen: true) { AutoFlush = true });
Console.Write('1');
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write('2');
Console.BackgroundColor = ConsoleColor.Red;
Console.Write('3');
Console.ResetColor();
Console.Write('4');
}
finally
{
Console.SetOut(savedOut);
}
const char Esc = (char)0x1B;
Assert.Equal(0, Encoding.UTF8.GetString(data.ToArray()).ToCharArray().Count(c => c == Esc));
Assert.Equal("1234", Encoding.UTF8.GetString(data.ToArray()));
}
示例3: Test
public static Boolean Test() {
String Text = "This is some test text";
Console.WriteLine("Original text : " + Text);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
cs.Write(Encoding.ASCII.GetBytes(Text), 0, Text.Length);
cs.Close();
Console.WriteLine("Encoded : " + Encoding.ASCII.GetString(ms.ToArray()));
MemoryStream ms1 = new MemoryStream();
CryptoStream cs1 = new CryptoStream(ms1, new FromBase64Transform(), CryptoStreamMode.Write);
cs1.Write(ms.ToArray(), 0, (int)ms.ToArray().Length);
cs1.Close();
Console.WriteLine("Decoded : " + Encoding.ASCII.GetString(ms1.ToArray()));
String mod = Encoding.ASCII.GetString((Byte[])ms.ToArray().Clone());
mod = mod.Insert(17, "\n").Insert(4, " ").Insert(8,"\t");
Byte[] modified = Encoding.ASCII.GetBytes(mod);
MemoryStream ms2 = new MemoryStream();
CryptoStream cs2 = new CryptoStream(ms2, new FromBase64Transform(), CryptoStreamMode.Write);
cs2.Write(modified, 0, (int)modified.Length);
cs2.Close();
Console.WriteLine("Decoded (with whitespaces) : " + Encoding.ASCII.GetString(ms2.ToArray()));
if (!Compare(ms1.ToArray(), ms2.ToArray())) return false;
return true;
}
示例4: CompressProfile
static void CompressProfile(string srcfile, string dstfile)
{
try
{
Console.WriteLine("Reading source...");
byte[] x = File.ReadAllBytes(srcfile);
int usize = x.Length;
Console.WriteLine("Initializing memory stream...");
MemoryStream ms = new MemoryStream();
// write uncompressed size as big endian
ms.WriteByte((byte)((usize>>24) & 0xFF));
ms.WriteByte((byte)((usize>>16) & 0xFF));
ms.WriteByte((byte)((usize>>8) & 0xFF));
ms.WriteByte((byte)(usize & 0xFF));
// then, compressed data
// these two bytes are part of zlib standard, but aren't supported by DeflateStream
ms.WriteByte(0x78);
ms.WriteByte(0x9C);
Console.WriteLine("Compressing data...");
MemoryStream compData = new MemoryStream();
DeflateStream ds = new DeflateStream(compData, CompressionMode.Compress);
ds.Write(x, 0, x.Length);
ds.Close();
ms.Write(compData.ToArray(), 0, compData.ToArray().Length);
// Adler32 checksum as big endian - also not supported by DeflateStream, but required by zlib standard
int checksum = GetAdler32(x);
ms.WriteByte((byte)((checksum>>24) & 0xFF));
ms.WriteByte((byte)((checksum>>16) & 0xFF));
ms.WriteByte((byte)((checksum>>8) & 0xFF));
ms.WriteByte((byte)(checksum & 0xFF));
// start filestream
Console.WriteLine("Creating file stream...");
FileStream fs = File.Create(dstfile);
// write hash
fs.Write(new SHA1CryptoServiceProvider().ComputeHash(ms.ToArray()), 0, 0x14);
// write usize + compressed data
fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
Console.WriteLine("Compression done.\n" + dstfile);
fs.Close();
ms.Close();
compData.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.GetType().Name + " | " + ex.Message);
Console.Beep();
}
return;
}
示例5: CheckContentFile
public void CheckContentFile ()
{
MemoryStream stream = new MemoryStream ();
package = Package.Open (stream, FileMode.Create, FileAccess.ReadWrite);
package.CreatePart (uris[0], "custom/type");
package.CreateRelationship (uris[1], TargetMode.External, "relType");
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.Open, FileAccess.ReadWrite);
package.Close ();
package = Package.Open (new MemoryStream (stream.ToArray ()), FileMode.Open, FileAccess.ReadWrite);
Assert.AreEqual (2, package.GetParts ().Count (), "#1");
Assert.AreEqual (1, package.GetRelationships ().Count (), "#2");
}
示例6: SendFileToClient
public void SendFileToClient(byte[] blob, string fullFilePath, bool asAttachment)
{
if (blob == null)
throw new ApplicationException("Can not view document. " + fullFilePath + " does not have an associated binary.");
FileInfo fi = new FileInfo(fullFilePath);
string displayName = fi.Name;
MemoryStream memStream = null;
try
{
// create the stream
memStream = new MemoryStream(blob);
m_context.Response.ClearHeaders();
m_context.Response.ClearContent();
m_context.Response.BufferOutput = true;
if (fi.Extension.ToLower() == ".pdf")
m_context.Response.ContentType = "application/pdf";
else
m_context.Response.ContentType = "application/octet-stream";
if (asAttachment)
{
// prompt
//m_context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
m_context.Response.AddHeader("Content-Disposition", "attachment; filename=" + displayName);
}
else
{
// don't prompt
m_context.Response.AddHeader("content-disposition", "inline; filename=" + displayName);
}
m_context.Response.OutputStream.Write(memStream.ToArray(), 0, memStream.ToArray().Length);
m_context.Response.Flush();
m_context.Response.Close();
}
catch (Exception ex)
{
m_context.Response.Write("Error : " + ex.Message);
}
finally
{
if (memStream != null)
memStream.Close();
}
}
示例7: Decrypt
//This method is to decrypt the password given by user.
public static string Decrypt(string data, string password)
{
if (String.IsNullOrEmpty(data))
throw new ArgumentException("No data given");
if (String.IsNullOrEmpty(password))
throw new ArgumentException("No password given");
byte[] rawData = Convert.FromBase64String(data.Replace(" ", "+"));
if (rawData.Length < 8)
throw new ArgumentException("Invalid input data");
// setup the decryption algorithm
byte[] salt = new byte[8];
for (int i = 0; i < salt.Length; i++)
salt[i] = rawData[i];
Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);
TripleDES tdes = TripleDES.Create();
//Rijndael aes = Rijndael.Create();
tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);
// decrypt the data
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(rawData, 8, rawData.Length - 8);
cryptoStream.Close();
byte[] decrypted = memoryStream.ToArray();
return Encoding.Unicode.GetString(decrypted);
}
}
开发者ID:progressiveinfotech,项目名称:PRO_FY13_40_Helpdesk-Support-and-Customization_HT,代码行数:35,代码来源:Login.aspx.cs
示例8: getImageValidate
//生成图像
private void getImageValidate(string strValue)
{
//string str = "OO00"; //前两个为字母O,后两个为数字0
int width = Convert.ToInt32(strValue.Length * 12); //计算图像宽度
Bitmap img = new Bitmap(width, 23);
Graphics gfc = Graphics.FromImage(img); //产生Graphics对象,进行画图
gfc.Clear(Color.White);
drawLine(gfc, img);
//写验证码,需要定义Font
Font font = new Font("arial", 12, FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush =
new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.DarkOrchid, Color.Blue, 1.5f, true);
gfc.DrawString(strValue, font, brush, 3, 2);
drawPoint(img);
gfc.DrawRectangle(new Pen(Color.DarkBlue), 0, 0, img.Width - 1, img.Height - 1);
//将图像添加到页面
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//更改Http头
Response.ClearContent();
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
//Dispose
gfc.Dispose();
img.Dispose();
Response.End();
}
示例9: OnBeforeSerialize
// Serialize object
public void OnBeforeSerialize()
{
// No need to serialize if the object is null
// or declared nonserializable
if (unserializable || unserializedObject == null)
return;
// Possible to loop over fields for serialization of (unity) non serializables
// This will prevent this method from blowing up when the serializer hits non serializable fields
// Possibly store all the fields in a dictionary of some kind? (increased memory usage, but more stable)
// For now just check one type
Type objType = unserializedObject.GetType();
// Check surrogates for non serializable types
if (!objType.IsSerializable)
{
if (!SurrogateHandler.GetSurrogate(ref unserializedObject))
{
Debug.Log("SerializableObject.Serialization: " + objType.ToString() + " is not a serializable type and has no surrogate");
unserializable = true;
return;
}
}
// Serialize
using(var stream = new MemoryStream())
{
var serializer = new BinaryFormatter();
serializer.Serialize(stream, unserializedObject);
byteArray = stream.ToArray();
}
//Debug.Log("Serialized Type: " + unserializedObject.GetType() + " | Value: " + unserializedObject.ToString());
}
示例10: ForCodeCoverage
public static bool ForCodeCoverage()
{
AesManaged aes = new AesManaged();
using (ICryptoTransform cte = aes.CreateEncryptor(), ctd = aes.CreateDecryptor())
{
byte[] plain1 = new byte[64];
for (int i = 0; i < plain1.Length; i++)
plain1[i] = (byte)i;
byte[] encr1 = cte.TransformFinalBlock(plain1, 0, plain1.Length);
using(MemoryStream ms = new MemoryStream())
using(CryptoStream cs = new CryptoStream(ms, ctd, CryptoStreamMode.Write))
{
cs.Write(encr1, 0, 16);
cs.Write(encr1, 16, 16);
cs.Write(encr1, 32, 16);
cs.Write(encr1, 48, encr1.Length-48);
cs.FlushFinalBlock();
byte[] plain2 = ms.ToArray();
if (!Compare(plain1, plain2))
{
Console.WriteLine("CodeCoverage case failed");
return false;
}
return true;
}
}
}
示例11: Save
public static void Save(string key, object obj)
{
MemoryStream memoryStream = new MemoryStream ();
binarryFormatter.Serialize (memoryStream, obj);
string tempResultStream = System.Convert.ToBase64String (memoryStream.ToArray ());
PlayerPrefs.SetString (key, tempResultStream);
}
示例12: DecryptString
public static string DecryptString(string input, string cryptographicProvider_PublicKey, string cryptographicProvider_IV)
{
try
{
input = input.Replace(CryptographicProviderKey, String.Empty);
using (var dataString = new MemoryStream())
{
var service = new TripleDESCryptoServiceProvider().CreateDecryptor(Encoding.UTF8.GetBytes(cryptographicProvider_PublicKey),
Encoding.UTF8.GetBytes(cryptographicProvider_IV));
using (var cryptoStream = new CryptoStream(dataString, service, CryptoStreamMode.Write))
{
var inputData = Convert.FromBase64String(input);
cryptoStream.Write(inputData, 0, inputData.Length);
cryptoStream.FlushFinalBlock();
var dataResult = dataString.ToArray();
var resultString = Encoding.UTF8.GetString(Convert.FromBase64String(Convert.ToBase64String(dataResult)));
cryptoStream.Close();
return resultString;
}
}
}
catch (Exception e)
{
return e.ToString();
}
}
示例13: BuildTree_PrintTree_ShouldWorkCorrectly
public void BuildTree_PrintTree_ShouldWorkCorrectly()
{
// Arrange
var tree =
new Tree<int>(7,
new Tree<int>(19,
new Tree<int>(1),
new Tree<int>(12),
new Tree<int>(31)),
new Tree<int>(21),
new Tree<int>(14,
new Tree<int>(23),
new Tree<int>(6)));
// Act
var outputStream = new MemoryStream();
using (var outputWriter = new StreamWriter(outputStream))
{
Console.SetOut(outputWriter);
tree.Print();
}
var output = Encoding.UTF8.GetString(outputStream.ToArray());
// Assert
var expectedOutput = "7\n 19\n 1\n 12\n 31\n 21\n 14\n 23\n 6\n";
output = output.Replace("\r\n", "\n");
Assert.AreEqual(expectedOutput, output);
}
示例14: OnBtnGenerateClicked
protected void OnBtnGenerateClicked(object sender, EventArgs e)
{
try {
BarcodeLib.Barcode codeBar = new BarcodeLib.Barcode ();
codeBar.Alignment = BarcodeLib.AlignmentPositions.CENTER;
codeBar.IncludeLabel = true;
codeBar.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
BarcodeLib.TYPE bCodeType = (BarcodeLib.TYPE)Enum.Parse (typeof(BarcodeLib.TYPE), cmbBarCodeType.ActiveText.ToString ());
System.Drawing.Image imgTmpCodeBar = codeBar.Encode (bCodeType, txtData.Text.Trim (), System.Drawing.Color.Black, System.Drawing.Color.White, 300, 300);
MemoryStream memoryStream = new MemoryStream();
imgTmpCodeBar.Save(memoryStream, ImageFormat.Png);
Gdk.Pixbuf pb = new Gdk.Pixbuf (memoryStream.ToArray());
imgCodeBar.Pixbuf = pb;
} catch (Exception err) {
MessageDialog dlg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, string.Format ("Ocurrió un error \n {0}", err.Message));
dlg.Run ();
dlg.Destroy ();
dlg.Dispose ();
dlg = null;
}
}
示例15: Main
public static int Main () {
MemoryStream mr = new MemoryStream();
BinaryWriter wr = new BinaryWriter(mr);
wr.Write ((byte) 1);
wr.Write ((int) 1);
wr.Write ((int) -1);
byte [] arr = mr.ToArray();
Console.Write ("Array (should be: 1 1 0 0 0 ff ff ff ff): ");
for (int a = 0; a != arr.Length; a++)
Console.Write(arr[a].ToString("x") + " ");
Console.WriteLine();
if (arr.Length != 9)
return 4;
if (arr[0] != 1)
return 1;
if (arr[1] != 1 && arr[2] != 0 && arr[3] != 0 && arr[4] != 0)
return 2;
if (arr[5] != 0xff && arr[6] != 0xff && arr[7] != 0xff && arr[8] != 0xff)
return 3;
Console.WriteLine("test-ok");
return 0;
}