本文整理汇总了C#中System.IO.MemoryStream.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# System.IO.MemoryStream.ToArray方法的具体用法?C# System.IO.MemoryStream.ToArray怎么用?C# System.IO.MemoryStream.ToArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.MemoryStream
的用法示例。
在下文中一共展示了System.IO.MemoryStream.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ToByteArray
public static byte[] ToByteArray(this System.IO.Stream strm)
{
if(strm is System.IO.MemoryStream)
{
return (strm as System.IO.MemoryStream).ToArray();
}
long originalPosition = -1;
if(strm.CanSeek)
{
originalPosition = strm.Position;
}
try
{
using (var ms = new System.IO.MemoryStream())
{
ms.CopyTo(ms);
return ms.ToArray();
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
if (originalPosition >= 0) strm.Position = originalPosition;
}
}
示例2: CreateImage
/// <summary>
/// 创建图片
/// </summary>
/// <param name="checkCode"></param>
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 11);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 19);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple };
Random rand = new Random();
//输出不同字体和颜色的验证码字符
for (int i = 0; i < checkCode.Length; i++)
{
int cindex = rand.Next(7);
Font f = new System.Drawing.Font("Microsoft Sans Serif", 11);
Brush b = new System.Drawing.SolidBrush(c[cindex]);
g.DrawString(checkCode.Substring(i, 1), f, b, (i * 10) + 1, 0, StringFormat.GenericDefault);
}
//画一个边框
g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
//输出到浏览器
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
示例3: SerializeVoxelAreaData
public static byte[] SerializeVoxelAreaData (VoxelArea v) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write (v.width);
writer.Write (v.depth);
writer.Write (v.linkedSpans.Length);
for (int i=0;i<v.linkedSpans.Length;i++) {
writer.Write(v.linkedSpans[i].area);
writer.Write(v.linkedSpans[i].bottom);
writer.Write(v.linkedSpans[i].next);
writer.Write(v.linkedSpans[i].top);
}
//writer.Close();
writer.Flush();
Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
stream.Position = 0;
zip.AddEntry ("data",stream);
System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
zip.Save(stream2);
byte[] bytes = stream2.ToArray();
stream.Close();
stream2.Close();
return bytes;
#else
throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
}
示例4: decodeAny
public override DecodedObject<object> decodeAny(DecodedObject<object> decodedTag, System.Type objectClass, ElementInfo elementInfo, System.IO.Stream stream)
{
int bufSize = elementInfo.MaxAvailableLen;
if (bufSize == 0)
return null;
System.IO.MemoryStream anyStream = new System.IO.MemoryStream(1024);
/*int tagValue = (int)decodedTag.Value;
for (int i = 0; i < decodedTag.Size; i++)
{
anyStream.WriteByte((byte)tagValue);
tagValue = tagValue >> 8;
}*/
if(bufSize<0)
bufSize = 1024;
int len = 0;
if (bufSize > 0)
{
byte[] buffer = new byte[bufSize];
int readed = stream.Read(buffer, 0, buffer.Length);
while (readed > 0)
{
anyStream.Write(buffer, 0, readed);
len += readed;
if (elementInfo.MaxAvailableLen > 0)
break;
readed = stream.Read(buffer, 0, buffer.Length);
}
}
CoderUtils.checkConstraints(len, elementInfo);
return new DecodedObject<object>(anyStream.ToArray(), len);
}
示例5: encryptRJ256
public static string encryptRJ256(string target, string key, string iv)
{
var rijndael = new System.Security.Cryptography.RijndaelManaged()
{
Padding = System.Security.Cryptography.PaddingMode.Zeros,
Mode = System.Security.Cryptography.CipherMode.CBC,
KeySize = 256,
BlockSize = 256
};
var bytesKey = Encoding.ASCII.GetBytes(key);
var bytesIv = Encoding.ASCII.GetBytes(iv);
var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv);
var msEncrypt = new System.IO.MemoryStream();
var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);
var toEncrypt = Encoding.ASCII.GetBytes(target);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
var encrypted = msEncrypt.ToArray();
return Convert.ToBase64String(encrypted);
}
示例6: ActionDefinition
public ActionDefinition(ActionLibrary parent, string name, int id)
{
Library = parent;
GameMakerVersion = 520;
Name = name;
ActionID = id;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Properties.Resources.DefaultAction.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
OriginalImage = ms.ToArray();
ms.Close();
Image = new System.Drawing.Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Drawing.Graphics.FromImage(Image).DrawImage(Properties.Resources.DefaultAction, new System.Drawing.Rectangle(0, 0, 24, 24), new System.Drawing.Rectangle(0, 0, 24, 24), System.Drawing.GraphicsUnit.Pixel);
(Image as System.Drawing.Bitmap).MakeTransparent(Properties.Resources.DefaultAction.GetPixel(0, Properties.Resources.DefaultAction.Height - 1));
Hidden = false;
Advanced = false;
RegisteredOnly = false;
Description = string.Empty;
ListText = string.Empty;
HintText = string.Empty;
Kind = ActionKind.Normal;
InterfaceKind = ActionInferfaceKind.Normal;
IsQuestion = false;
ShowApplyTo = true;
ShowRelative = true;
ArgumentCount = 0;
Arguments = new ActionArgument[8];
for (int i = 0; i < 8; i++) Arguments[i] = new ActionArgument();
ExecutionType = ActionExecutionType.None;
FunctionName = string.Empty;
Code = string.Empty;
}
示例7: SaveWebPost
private void SaveWebPost(string fileName, PostModel model)
{
WebPostModel wPost = new WebPostModel()
{
PTitle = model.PTitle,
PText = model.PText,
PLink = model.PLink,
PImage = model.PImage,
PDate = model.PDate.ToString("yyyy-MM-ddTHH:mm:ss"),
PPrice = model.PPrice
};
System.IO.MemoryStream msPost = new System.IO.MemoryStream();
System.Runtime.Serialization.Json.DataContractJsonSerializer dcJsonPost =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WebPostModel));
dcJsonPost.WriteObject(msPost, wPost);
using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
{
byte[] jsonArray = msPost.ToArray();
using (System.IO.Compression.GZipStream gz =
new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress))
{
gz.Write(jsonArray, 0, jsonArray.Length);
}
}
}
示例8: Main
static void Main(string[] args)
{
Sodao.FastSocket.SocketBase.Log.Trace.EnableConsole();
Sodao.FastSocket.SocketBase.Log.Trace.EnableDiagnostic();
var client = new Sodao.FastSocket.Client.AsyncBinarySocketClient(8192, 8192, 3000, 3000);
//注册服务器节点,这里可注册多个(name不能重复)
client.RegisterServerNode("127.0.0.1:8401", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8401));
//client.RegisterServerNode("127.0.0.1:8402", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.2"), 8401));
//组织sum参数, 格式为<<i:32-limit-endian,....N>>
//这里的参数其实也可以使用thrift, protobuf, bson, json等进行序列化,
byte[] bytes = null;
using (var ms = new System.IO.MemoryStream())
{
for (int i = 1; i <= 1000; i++) ms.Write(BitConverter.GetBytes(i), 0, 4);
bytes = ms.ToArray();
}
//发送sum命令
client.Send("sum", bytes, res => BitConverter.ToInt32(res.Buffer, 0)).ContinueWith(c =>
{
if (c.IsFaulted)
{
// Console.WriteLine(c.Exception.ToString());
return;
}
// Console.WriteLine(c.Result);
});
Console.ReadLine();
}
示例9: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
// 用于显示的数字.
string number = Request["NO"];
if (String.IsNullOrEmpty(number))
{
number = "123456";
}
// 定义图片大小.
System.Drawing.Bitmap image =
new System.Drawing.Bitmap(400, 200);
Graphics g = Graphics.FromImage(image);
// 字体.
Font codeFont = new System.Drawing.Font("Vijaya", 32, (System.Drawing.FontStyle.Bold));
LinearGradientBrush brush =
new LinearGradientBrush(
new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.White, 1.2f, true);
g.DrawString(number, codeFont, brush, 20, 20);
// 用于模拟图片长时间下载.
Thread.Sleep(2500);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
示例10: Write
public void Write(string key, LocationCacheRecord lcr)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
formatter.Serialize(ms, lcr);
cache.Write(key, ms.ToArray(), true);
}
示例11: GetMessagesData
public override IData GetMessagesData(IList<Message> messages)
{
IData data = null;
byte[] buffer;
long index = 0;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
foreach (Message message in messages)
{
stream.Write(new byte[4], 0, 4);
short typevalue = TypeMapper.GetValue(message.Type);
if (typevalue == 0)
throw new Exception (string.Format ("{0} type value not registed", message.Type));
byte[] typedata = BitConverter.GetBytes(typevalue);
stream.Write(typedata, 0, typedata.Length);
if (message.Value != null)
ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(stream, message.Value);
buffer = stream.GetBuffer();
BitConverter.GetBytes((int)stream.Length - 4 - (int)index).CopyTo(buffer, index);
index = stream.Position;
}
byte[] array = stream.ToArray();
data = new Data(array,0, array.Length);
}
return data;
}
示例12: QRCode
//Look at http://code.google.com/p/zxing/wiki/BarcodeContents for formatting
/// <summary>
/// Returns a QRCode with the data embedded
/// </summary>
/// <param name="data">The data to embed in a QRCode.</param>
public Task<ImageResult> QRCode(string data)
{
return AsyncHelper.RunAsync(() =>
{
var qrCode = new MultiFormatWriter();
var byteIMG = qrCode.encode(data, BarcodeFormat.QR_CODE, 200, 200);
sbyte[][] img = byteIMG.Array;
var bmp = new Bitmap(200, 200);
var g = Graphics.FromImage(bmp);
g.Clear(Color.White);
for (var y = 0; y <= img.Length - 1; y++)
{
for (var x = 0; x <= img[y].Length - 1; x++)
{
g.FillRectangle(
img[y][x] == 0 ? Brushes.Black : Brushes.White, x, y, 1, 1);
}
}
var stream = new System.IO.MemoryStream();
bmp.Save(stream, ImageFormat.Jpeg);
var imageBytes = stream.ToArray();
stream.Close();
return this.Image(imageBytes, "image/jpeg");
});
}
示例13: SubmitResult
public static void SubmitResult(Uri testVaultServer, string session, string project, string buildname, string testgroup, string testname, TestOutcome outcome, bool personal)
{
try
{
using ( var client = new WebClient() ){
client.BaseAddress = testVaultServer.ToString();
client.CachePolicy = new System.Net.Cache.RequestCachePolicy( System.Net.Cache.RequestCacheLevel.NoCacheNoStore );
client.Headers.Add("Content-Type", "text/xml");
var result = new TestResult()
{
Group = new TestGroup() { Name = testgroup, Project = new TestProject() { Project = project } },
Name = testname,
Outcome = outcome,
TestSession = session,
IsPersonal = personal,
BuildID = buildname,
};
var xc = new XmlSerializer(result.GetType());
var io = new System.IO.MemoryStream();
xc.Serialize( io, result );
client.UploadData( testVaultServer.ToString(), io.ToArray() );
}
} catch ( Exception e )
{
Console.Error.WriteLine( e );
}
}
示例14: Build
public static byte[] Build(Xml.FileGroupXml group, string spriteFile)
{
var bmps = group.Files.Select(x => new System.Drawing.Bitmap(x.Path));
var maxWidth = bmps.Max(x => x.Width);
var totalHeight = bmps.Sum(x => x.Height);
int top = 0;
using (var sprite = new System.Drawing.Bitmap(maxWidth, totalHeight))
using (var mem = new System.IO.MemoryStream())
using (var g = System.Drawing.Graphics.FromImage(sprite))
{
foreach (var bmp in bmps)
{
using (bmp)
{
g.DrawImage(bmp, new System.Drawing.Rectangle(0, top, bmp.Width, bmp.Height), new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.GraphicsUnit.Pixel);
top += bmp.Height;
}
}
sprite.Save(mem, GetFormat(spriteFile) ?? System.Drawing.Imaging.ImageFormat.Png);
return mem.ToArray();
}
}
示例15: PngIconFromImage
public static Icon PngIconFromImage(Image img, int size = 16)
{
using (var bmp = new Bitmap(img, new Size(size, size)))
{
byte[] png;
using (var fs = new System.IO.MemoryStream())
{
bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
fs.Position = 0;
png = fs.ToArray();
}
using (var fs = new System.IO.MemoryStream())
{
if (size >= 256) size = 0;
Pngiconheader[6] = (byte)size;
Pngiconheader[7] = (byte)size;
Pngiconheader[14] = (byte)(png.Length & 255);
Pngiconheader[15] = (byte)(png.Length / 256);
Pngiconheader[18] = (byte)(Pngiconheader.Length);
fs.Write(Pngiconheader, 0, Pngiconheader.Length);
fs.Write(png, 0, png.Length);
fs.Position = 0;
return new Icon(fs);
}
}
}