本文整理汇总了C#中System.IO.MemoryStream.CopyTo方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.CopyTo方法的具体用法?C# MemoryStream.CopyTo怎么用?C# MemoryStream.CopyTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.MemoryStream
的用法示例。
在下文中一共展示了MemoryStream.CopyTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CopyTo1
public unsafe void CopyTo1()
{
const int bufferSize = 10;
byte* buffer = (byte*)Marshal.AllocHGlobal(bufferSize);
try
{
var s = new MemoryStream(new byte[] { 0, 1, 2, 3, 4 });
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, 3);
Assert.Equal(new byte[] { 0, 1, 2 }, ReadBuffer(buffer, bufferSize));
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, 0);
Assert.Equal(new byte[0], ReadBuffer(buffer, bufferSize));
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, 5);
Assert.Equal(new byte[] { 0, 1, 2, 3, 4 }, ReadBuffer(buffer, bufferSize));
Assert.Throws<IOException>(() => s.CopyTo(buffer, 6));
}
finally
{
Marshal.FreeHGlobal((IntPtr)buffer);
}
}
示例2: CompressResponse
private Response CompressResponse(Request request, Response response)
{
if (!response.ContentType.Contains("image")
&& request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"))
&& (!response.Headers.ContainsKey("Content-Encoding") || response.Headers["Content-Encoding"] != "gzip"))
{
var data = new MemoryStream();
response.Contents.Invoke(data);
data.Position = 0;
if (data.Length < 1024)
{
response.Contents = stream =>
{
data.CopyTo(stream);
stream.Flush();
};
}
else
{
response.Headers["Content-Encoding"] = "gzip";
response.Contents = s =>
{
var gzip = new GZipStream(s, CompressionMode.Compress, true);
data.CopyTo(gzip);
gzip.Close();
};
}
}
return response;
}
示例3: Zip
public static byte[] Zip(List<Tuple<string, byte[]>> files)
{
using (var compressedFileStream = new MemoryStream())
{
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
{
foreach (var file in files)
{
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry(file.Item1);
//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(file.Item2))
{
using (var zipEntryStream = zipEntry.Open())
{
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}
}
return compressedFileStream.ToArray();
}
}
示例4: Main
static void Main(string[] args)
{
if (args == null || args.Length != 2)
Console.WriteLine("Usage: <source folder> <destinaion file>");
var source = new DirectoryInfo(args[0]);
if (!source.Exists)
throw new ApplicationException("Source folder does not exist");
var destination = new FileInfo(args[1]);
if (destination.Exists)
throw new ApplicationException("Destination already exists");
// mem-stream needs to be here for this to work?
using (var destinationStream = destination.OpenWrite())
using (var memStream = new MemoryStream())
using (var lz4Stream = new LZ4Stream(destinationStream, CompressionMode.Compress, true, true))
{
using (var zipArchive = new ZipArchive(memStream, ZipArchiveMode.Create, true))
AddFilesToArchive(source, "", zipArchive);
memStream.Position = 0;
memStream.CopyTo(lz4Stream);
}
}
示例5: Archive
public static ZipFileMock Archive(string sourceDirectoryName, string destinationArchiveFileName, params FileMock[] files)
{
var bytes = new byte[0];
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
var relativePath = PathHelper.Subtract(file.Path, sourceDirectoryName);
var entry = archive.CreateEntry(relativePath);
using (var entryStream = entry.Open())
{
entryStream.Write(file.Bytes, 0, file.Bytes.Length);
entryStream.Flush();
}
}
}
// Fix for "invalid zip archive"
using ( var fileStream = new MemoryStream() )
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
bytes = fileStream.ToArray();
}
}
var zipFile = new ZipFileMock(destinationArchiveFileName, bytes, files);
return zipFile;
}
示例6: Compress
public static byte[] Compress(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
using (var output = new MemoryStream())
{
// ZLib Header 0x78 0x9C
output.WriteByte(0x78);
output.WriteByte(0x9C);
using (var input = new MemoryStream(data))
{
using (var compressionStream = new DeflateStream(output, CompressionMode.Compress, true))
{
input.CopyTo(compressionStream);
compressionStream.Close();
// Adler32 hash of the uncompressed data
var adler32 = new Adler32();
adler32.Update(data);
byte[] hash = BitConverter.GetBytes((int) adler32.Value);
Array.Reverse(hash);
output.Write(hash, 0, hash.Length);
return output.ToArray();
}
}
}
}
示例7: ProcessImage
public static async Task ProcessImage(
[QueueInput("uploads")] Message message,
[BlobInput("uploads/{BlobName}")] Stream input,
[BlobOutput("memes/{BlobName}")] Stream output)
{
var encoder = new AnimatedGifEncoder();
encoder.SetRepeat(0);
int delay;
var frames = ProcessInputFrames(input, message.OverlayText.ToUpperInvariant(), out delay);
encoder.SetDelay(delay);
using (var result = new MemoryStream())
{
encoder.Start(result);
var idx = 1;
foreach (var frame in frames)
{
Console.WriteLine("Adding frame #{0}/{1}", idx, frames.Count);
encoder.AddFrame(frame);
idx++;
}
encoder.Finish();
result.Position = 0;
result.CopyTo(output);
}
var uri = SetMetadataAndCleanup(message);
await SendCompleteNotification(message, uri);
}
示例8: onPost
public void onPost(string light, string hum, string temp, Stream fileCont)
{
// save POST content as BMP file ...
string docname = (DateTime.Now.ToLongTimeString() + "." + light + "_" + hum + "_" + temp + ".bmp").Replace(":", "_");
string strdocPath;
strdocPath = System.Web.Hosting.HostingEnvironment.MapPath("~/pics/") + docname;
// Save Stream to local memory stream for later distrbution ...
var ms = new MemoryStream();
fileCont.CopyTo(ms);
ms.Position = 0;
FileStream fs = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
ms.CopyTo(fs);
ms.Position = 0;
fs.Close(); ;
Byte[] bytes = new Byte[ms.Length];
ms.Read(bytes, 0, bytes.Length);
var objContext = new TDataEntities();
var newData = new TDataItem();
newData.lightSENS = int.Parse(light);
newData.humSENS = int.Parse(hum);
newData.tempSENS = decimal.Parse(temp);
newData.Date = DateTime.Now;
newData.Transacto = bytes;
objContext.TDataItems.AddObject(newData);
objContext.SaveChanges();
}
示例9: CopyTo2
public unsafe void CopyTo2()
{
const int bufferSize = 2 * StreamExtensions.StreamCopyBufferSize;
byte* buffer = (byte*)Marshal.AllocHGlobal(bufferSize);
try
{
var a = new byte[StreamExtensions.StreamCopyBufferSize + 1];
for (int i = 0; i < a.Length; i++)
{
a[i] = 1;
}
a[a.Length - 2] = 2;
a[a.Length - 1] = 3;
var s = new MemoryStream(a);
InvalidateMemory(buffer, bufferSize);
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(buffer, a.Length);
Assert.Equal(a, ReadBuffer(buffer, bufferSize));
}
finally
{
Marshal.FreeHGlobal((IntPtr)buffer);
}
}
示例10: Write
public override void Write(ref NetworkStream netstream)
{
using (Stream stream = new MemoryStream())
{
// write id
stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2);
// write temporary size
stream.Write(BitConverter.GetBytes(0), 0, 4);
// store header size
int headersize = (int)stream.Position;
// write name
stream.WriteByte((byte)this.Name.Length);
stream.Write(Encoding.ASCII.GetBytes(this.Name), 0, this.Name.Length);
// write exists
stream.WriteByte(BitConverter.GetBytes(this.Exists)[0]);
// go back and write body size
this.BodySize = (uint)(stream.Length - headersize);
stream.Position = 2;
stream.Write(BitConverter.GetBytes(this.BodySize), 0, 4);
// copy stream to netstream
stream.Position = 0;
stream.CopyTo(netstream);
}
}
示例11: DecryptDataAsBytes
private static byte[] DecryptDataAsBytes(byte[] encryptedData, string privateKeyPem, string publicKeyPem)
{
using (var encryptedDataStream = new MemoryStream(encryptedData))
using (var encryptedDataWithoutKeyPair = new MemoryStream())
{
var signatureLengthBytes = new byte[4];
var bytesRead = encryptedDataStream.Read(signatureLengthBytes, 0, 4);
if (bytesRead == -1)
throw new Exception("Unexpected end of encrypted data (expected encrypted key size)");
var signatureLength = BitConverter.ToInt32(signatureLengthBytes, 0);
var signature = new byte[signatureLength];
bytesRead = encryptedDataStream.Read(signature, 0, signatureLength);
if (bytesRead != signatureLength)
throw new Exception("Unexpected end of encrypted data (expected encrypted key)");
encryptedDataStream.CopyTo(encryptedDataWithoutKeyPair);
var decryptedData = EncryptedDataWithKeyPair.DecryptDataAsBytes(
encryptedDataWithoutKeyPair.ToArray(), privateKeyPem);
var signatureVerified = AsymmetricCryptoUtil.VerifySignature(decryptedData, signature, publicKeyPem);
if (!signatureVerified)
throw new Exception("Message could not be verified");
return decryptedData;
}
}
示例12: Clone
// Call this to create a new stream based on the bytes of the current one
// It creates a temporary stream because it may already be disposed
public LocalMemoryStream Clone()
{
var ms = new MemoryStream(this.ToArray());
var local = new LocalMemoryStream();
ms.CopyTo(local);
return local;
}
示例13: ResponseCallBack
private static void ResponseCallBack(IAsyncResult asynchronousResult)
{
var requestData = (RequestState) asynchronousResult.AsyncState;
ConsoleUtilities.WriteResponse("Proxy receive a response from " + requestData.context.Request.RawUrl);
using (var responseFromWebSiteBeingRelayed = (HttpWebResponse) requestData.webRequest.EndGetResponse(asynchronousResult))
{
using (var responseStreamFromWebSiteBeingRelayed = responseFromWebSiteBeingRelayed.GetResponseStream())
{
var originalResponse = requestData.context.Response;
if (responseFromWebSiteBeingRelayed.ContentType.Contains("text/html"))
{
var reader = new StreamReader(responseStreamFromWebSiteBeingRelayed);
string html = reader.ReadToEnd();
//Here can modify html
byte[] byteArray = System.Text.Encoding.Default.GetBytes(html);
var stream = new MemoryStream(byteArray);
stream.CopyTo(originalResponse.OutputStream);
}
else
{
responseStreamFromWebSiteBeingRelayed.CopyTo(originalResponse.OutputStream);
}
originalResponse.OutputStream.Close();
}
}
}
示例14: Send
public override void Send(Message[] messages)
{
try
{
lock (this)
{
MemoryStream local_0 = new MemoryStream();
BinaryWriter local_1 = new BinaryWriter((Stream)local_0);
foreach (Message item_0 in messages)
{
local_1.Write(item_0.Type);
item_0.GetData(local_1);
}
local_1.Flush();
byte[] local_3 = BitConverter.GetBytes((int)local_0.Length);
this.SlIRVIT0r.Write(local_3, 0, local_3.Length);
local_0.Position = 0L;
local_0.CopyTo((Stream)this.SlIRVIT0r);
}
}
catch (Exception ex)
{
this.Close();
throw ex;
}
}
示例15: GenerateThumbnails
public void GenerateThumbnails(ThumbnailGenerationParameters parameters)
{
var textureConverterFactory = new TextureConverterFactory();
using (var textureConverter = textureConverterFactory.Create()) {
IFilter grayscaleFilter = new Grayscale(0.3, 0.59, 0.11);
IInPlaceFilter edgeDetectionFilter = new HomogenityEdgeDetector();
SliceRatingCalculator ratingCalculator = new SliceRatingCalculator();
var utilities = new ThumbnailGeneratorUtilities(textureConverter);
var slicePicker = new SlicePicker(grayscaleFilter, edgeDetectionFilter, ratingCalculator, utilities);
var aspectRatio = 16 / (double)9;
var sliceCount = 5;
var resultWidth = 400;
var resultHeight = (int)(resultWidth / aspectRatio);
var sliceWidth = resultWidth / sliceCount;
var bitmaps = utilities.EnumerateBitmapsRandomly(parameters.SourceDirectory).Take(100).ToList();
var slices = slicePicker.PickSlices(bitmaps, new Size(sliceWidth, resultHeight));
var sliceCombiner = new SliceCombiner(utilities, grayscaleFilter);
for (var i = 0; i < parameters.ThumbnailsToGenerate; i++) {
var bitmap = sliceCombiner.CombineSlices(slices, kSlicesPerThumbnail);
using (var ms = new MemoryStream()) {
bitmap.Save(ms, ImageFormat.Jpeg);
ms.Position = 0;
var hash = MD5.Create().ComputeHash(ms).ToHex();
var outputName = hash + "_" + DateTime.UtcNow.GetUnixTime().ToString() + ".jpg";
var outputPath = Path.Combine(parameters.DestinationDirectory, outputName);
ms.Position = 0;
using (var fs = File.OpenWrite(outputPath)) {
ms.CopyTo(fs);
}
}
}
}
}