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); } }
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; }
// export Artwork out to a disk file public void exportArtwork(string filepath) { if (artwork == null) { throw new InvalidOperationException("Cannot Export artwork out of Bundle, no Artwork present"); } using (FileStream fsOutput = new FileStream(filepath, FileMode.Create)) { artwork.Seek(0, SeekOrigin.Begin); artwork.CopyTo(fsOutput); } }
public void Save(string filename, string contentType, MemoryStream stream) { string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } if (contentType == "application/html" || exception != string.Empty) return; UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; UIView currentView = currentController.View; QLPreviewController qlPreview = new QLPreviewController(); QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); qlPreview.DataSource = new PreviewControllerDS(item); //UIViewController uiView = currentView as UIViewController; currentController.PresentViewController((UIViewController)qlPreview, true, (Action)null); }
public override byte[] Encode(byte[] bytes) { using (var inputstr = new MemoryStream(bytes)) using (var outputstr = new MemoryStream()) { // http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like // http://stackoverflow.com/questions/18450297/is-it-possible-to-use-the-net-deflatestream-for-pdf-creation // https://web.archive.org/web/20130905215303/http://connect.microsoft.com/VisualStudio/feedback/details/97064/deflatestream-throws-exception-when-inflating-pdf-streams //#if IONIC using (var dstream = new Ionic.Zlib.ZlibStream(outputstr, Ionic.Zlib.CompressionMode.Compress)) { dstream.FlushMode = Ionic.Zlib.FlushType.Finish; //#elif NET40 // using (var dstream = new System.IO.Compression.DeflateStream(outputstr, System.IO.Compression.CompressionMode.Compress)) // { // // Zlib magic header (Default Compression): // outputstr.WriteByte(0x78); // outputstr.WriteByte(0x9C); //#else //NET45+ // using (var dstream = new System.IO.Compression.DeflateStream(outputstr, System.IO.Compression.CompressionLevel.Optimal)) // { // // Zlib magic header (Best Compression): // outputstr.WriteByte(0x78); // outputstr.WriteByte(0xDA); //#endif inputstr.CopyTo(dstream); inputstr.Flush(); } return outputstr.ToArray(); } }
public void Decrypt(System.IO.Stream input, System.IO.Stream output, string password) { if(input == null) throw new System.ArgumentNullException("input"); if(output == null) throw new System.ArgumentNullException("output"); if(string.IsNullOrEmpty(password)) throw new System.ArgumentException("Must not be null or empty.", "password"); byte[] hashedPassword = HashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = Algorithm.CreateDecryptor(hashedPassword.Take(32).ToArray(), hashedPassword.Skip(48).ToArray()); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { input.CopyTo(csEncrypt); csEncrypt.FlushFinalBlock(); msEncrypt.Position = 0; msEncrypt.CopyTo(output); } } }
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); } }
public void CriarArquivoLog(List <string> mensagem, string url, string usuario, string senha) { string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; Trace.Add("CriarArquivoLog - URL {0} USERNAME: {1}", url, userName); Trace.Add("MensagemArquivoLog - {0} ", mensagem); StringBuilder sb = new StringBuilder(); foreach (string item in mensagem) { sb.AppendLine(item); } Uri destUri = new Uri(url); using (MemoryStream inStream = new System.IO.MemoryStream(Encoding.Default.GetBytes(sb.ToString()))) { WebRequest request = WebRequest.Create(url); request.Credentials = new NetworkCredential(usuario, senha); request.Method = "PUT"; request.Timeout = 10000; request.ContentType = "text/plain;charset=utf-8"; using (Stream outStream = request.GetRequestStream()) { inStream.CopyTo(outStream); } WebResponse res = request.GetResponse(); } }
/// <summary> /// Compresses a buffer of bytes. /// </summary> /// <param name="array">Array to bytes to compress.</param> public byte[] Compress(byte[] array) { byte[] output = null; using (MemoryStream inStream = new MemoryStream(array)) { using (MemoryStream outStream = new MemoryStream()) { using (GZipStream compressionStream = new GZipStream(outStream, CompressionLevel.Fastest)) { inStream.CopyTo(compressionStream); } output = outStream.ToArray(); } } // Only use if the compressed array is smaller. byte[] finalArray = new byte[1 + (output.Length < array.Length ? output.Length : array.Length)]; if (output.Length < array.Length) { finalArray[0] = 1; output.CopyTo(finalArray, 1); } else { finalArray[0] = 0; array.CopyTo(finalArray, 1); } return finalArray; }
public override void Write(ref NetworkStream netstream) { using (Stream stream = new MemoryStream()) { // write Packet ID stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2); // write Packet Size stream.Write(BitConverter.GetBytes(this.BodySize), 0, 4); // write UserID stream.WriteByte((byte)this.UserID.Length); stream.Write(Encoding.ASCII.GetBytes(this.UserID), 0, this.UserID.Length); // write PCName stream.WriteByte((byte)this.PCName.Length); stream.Write(Encoding.ASCII.GetBytes(this.PCName), 0, this.PCName.Length); // write AuthKey stream.Write(BitConverter.GetBytes(this.AuthKey), 0, 4); // copy stream to netstream stream.Position = 0; stream.CopyTo(netstream); } }
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); } }
// 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; }
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; } }
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(); } } } }
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(); } } }
public async Task SaveTextAsync(string filename,string contentType, MemoryStream s) { string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string filePath = Path.Combine(path,filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); s.Position=0; s.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { } UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; UIView currentView = currentController.View; QLPreviewController qlPreview = new QLPreviewController(); QLPreviewItem item= new QLPreviewItemBundle(filename,filePath); qlPreview.DataSource = new PreviewControllerDS(item); currentController.PresentViewController (qlPreview, true, null); }
public static string Compress(string inputString, Compressor compressor = Compressor.Deflate) { try { byte[] input = Encoding.UTF8.GetBytes(inputString); using (MemoryStream inmemoryStream = new MemoryStream(input)) { using (MemoryStream outmemoryStream = new MemoryStream()) { Stream zipStream = (compressor == Compressor.Deflate ? new DeflateStream(outmemoryStream, CompressionMode.Compress) as Stream : new GZipStream(outmemoryStream, CompressionMode.Compress) as Stream); using (zipStream) { inmemoryStream.CopyTo(zipStream); } byte[] output = outmemoryStream.ToArray(); return Convert.ToBase64String(output); } } } catch (Exception ex) { ex.GetType(); return null; } }
public void WriteNewKernel(Stream kernel, Stream output) { var writer = new XeWriter(output); writer.WriteUInt16(magic); writer.WriteUInt16(version); writer.WriteUInt16(unkWord1); writer.WriteUInt16(unkWord2); writer.WriteUInt32(entryPoint); writer.WriteUInt32(0xdeadbeef); // Will need to go back and update after compression writer.Write(hmacSalt, 0, 0x10); var meta = new byte[0x10]; BufferUtils.FromUInt32((uint)kernel.Length, meta, 0x08); writer.Write(meta, 0, 0x10); var compressedKernelStream = new MemoryStream(); CompressKernel(kernel, compressedKernelStream); compressedKernelStream.Seek(0, SeekOrigin.Begin); compressedKernelStream.CopyTo(output); compressedKernelStream.Close(); writer.Seek(0x0c, SeekOrigin.Begin); writer.WriteUInt32((uint)writer.Length); }
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); } } } } }
private async void download(object sender, RoutedEventArgs e) { var item = listview.SelectedItem as CloudBlockBlob; var blob = App.container.GetBlockBlobReference(item.Name); StorageFile file; try { if (listview.SelectedIndex != -1) { file = await temporaryFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting); using (var fileStream = await file.OpenStreamForWriteAsync()) { var outputstream = fileStream.AsOutputStream(); //Hither InMemoryRandomAccessStream decstream = new InMemoryRandomAccessStream(); System.IO.Stream netstream = System.IO.WindowsRuntimeStreamExtensions.AsStreamForRead(decstream); //Hence Stream saveStr = new System.IO.MemoryStream(); IOutputStream winStr = System.IO.WindowsRuntimeStreamExtensions.AsOutputStream(saveStr); // var bufferstream = outputstream.AsStreamForWrite(UInt16.MaxValue); await blob.DownloadToStreamAsync(winStr); saveStr.Position = 0; saveStr.CopyTo(fileStream); fileStream.Flush(); } // Make sure it's an image file. imgbox.Source = new BitmapImage(new Uri(file.Path)); IbState.Text = "Success\n" + file.Path; } } catch (Exception ex) { IbState.Text += (ex.Message + "\n"); } }
public void ShouldCopyOneStreamToAnother() { var input = new MemoryStream(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0xfe, 0xff }); var output = new MemoryStream(); input.CopyTo(output); CollectionAssert.AreEqual(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0xfe, 0xff }, output.ToArray()); }
public override void Write(ref NetworkStream netstream) { using (Stream stream = new MemoryStream()) { // write id stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2); // write body size stream.Write(BitConverter.GetBytes(0), 0, 4); // write isAdult stream.WriteByte(BitConverter.GetBytes(this.isAdult)[0]); // write UnderFifteen stream.WriteByte(BitConverter.GetBytes(this.UnderFifteen)[0]); // write Family stream.WriteByte(BitConverter.GetBytes(this.Family)[0]); // write Status stream.WriteByte(this.Status); // write LastDay stream.Write(BitConverter.GetBytes(this.LastDay), 0, 2); // write PayType stream.WriteByte(this.PayType); // copy stream to netstream stream.Position = 0; stream.CopyTo(netstream); } }
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); } }
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; } }
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(); }
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); }
protected void Page_Load(object sender, EventArgs e) { Bitmap bitMapImage = new Bitmap(Server.MapPath("certificate-format.jpg")); Graphics graphicImage = Graphics.FromImage(bitMapImage); graphicImage.SmoothingMode = SmoothingMode.AntiAlias; // Student name string studentName = RandomString(8) + " " + RandomString(4); // Write text on it graphicImage.DrawString(studentName, new Font("Arial", 20, FontStyle.Bold), SystemBrushes.WindowText, new Point(300, 250)); // Draw QR Code, for demo i'll be using seal.png image var barCodeImageSrc = new Bitmap(Server.MapPath("seal.png")); // File source maybe generated QR Code graphicImage.DrawImage(barCodeImageSrc, new Point(570, 400)); // Save Bitmap to stream var memStream = new MemoryStream(); bitMapImage.Save(memStream, ImageFormat.Jpeg); // Save memory stream into file var fileName = new Random().Next().ToString(); using (var fileStream = new FileStream(Server.MapPath("~/Certificates/") + fileName + ".jpg", FileMode.Append, FileAccess.Write)) { memStream.Position = 0; memStream.CopyTo(fileStream); } Response.Redirect("~/Certificate.aspx?id=" + fileName); }
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; }
/// <summary> /// Post processes the image. /// </summary> /// <param name="stream">The source image stream.</param> /// <param name="extension">The image extension.</param> /// <returns> /// The <see cref="MemoryStream"/>. /// </returns> public static MemoryStream PostProcessImage(MemoryStream stream, string extension) { // Create a source temporary file with the correct extension. long length = stream.Length; string tempFile = Path.GetTempFileName(); string sourceFile = Path.ChangeExtension(tempFile, extension); File.Move(tempFile, sourceFile); // Save the input stream to a temp file for post processing. using (FileStream fileStream = File.Create(sourceFile)) { stream.CopyTo(fileStream); } PostProcessingResultEventArgs result = RunProcess(sourceFile, length); if (result != null && result.Saving > 0) { using (FileStream fileStream = File.OpenRead(sourceFile)) { // Replace stream contents. stream.SetLength(0); fileStream.CopyTo(stream); } } // Cleanup File.Delete(sourceFile); stream.Position = 0; return stream; }
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(); } }
public void ProcessRequest(HttpContext context) { int width = 600; int height = 400; var imageAsText = context.Request.Url.ToString(); using (Bitmap bitmap = new Bitmap(width, height)) { Graphics graphics = Graphics.FromImage(bitmap); graphics.FillRectangle(Brushes.Red, 0f, 0f, bitmap.Width, bitmap.Height); graphics.DrawString(imageAsText, new Font("Consolas", 20, FontStyle.Underline), SystemBrushes.WindowText, new PointF(10, 40)); using (MemoryStream mem = new MemoryStream()) { bitmap.Save(mem, ImageFormat.Png); mem.Seek(0, SeekOrigin.Begin); context.Response.ContentType = "image/png"; mem.CopyTo(context.Response.OutputStream, 4096); context.Response.Flush(); } } }
public List<string> LoadCVM(Stream iso_file, string cvmOpen) { List<string> files = new List<string>(); try { using (MemoryStream mt = new MemoryStream()) { CDReader cr = new CDReader(iso_file, true); MemoryStream mem = new MemoryStream((int)iso_file.Length); cr.OpenFile(cvmOpen, FileMode.Open).CopyTo(mem); mem.Seek(0x1800, SeekOrigin.Begin); mem.CopyTo(mt); mem.Dispose(); mem.Close(); CDReader cvmRead = new CDReader(mt, true); DiscUtils.DiscFileInfo[] filescvm = cvmRead.Root.GetFiles("*.*", SearchOption.AllDirectories); foreach (DiscUtils.DiscFileInfo file in filescvm) { files.Add(file.FullName.ToString()); } mt.Dispose(); mt.Close(); return files; } } catch (OutOfMemoryException) { return null; } }
public static void saveRawFrame(System.IO.MemoryStream data, AvcCBox avcC, string f) {//throws IOException { Stream raw = new System.IO.FileStream(f, FileMode.OpenOrCreate); saveStreamParams(avcC, raw); data.CopyTo(raw); raw.Close(); }
//--------------------------------------------------------------------------------------------- /// <summary> /// This method creates a Plan Quality Metric report for the specified plansum. /// </summary> /// <param name="patient">loaded patient</param> /// <param name="ss">structure set to use while generating Plan Quality Metrics</param> /// <param name="psum">Plansum for which the report is going to be generated.</param> /// <param name="rootPath">root directory for the report. This method creates a subdirectory /// 'patientid' under the root, then creates the xml and html reports in the subdirectory.</param> /// <param name="userId">User whose id will be stamped on the report.</param> //--------------------------------------------------------------------------------------------- override protected void dumpReportXML(Patient patient, StructureSet ss, PlanningItem plan_, string sXMLPath) { if (!(plan_ is PlanSum)) { throw new ApplicationException("PlanSumReporter should be used only for PlanSum types!"); } PlanSum psum = (PlanSum)plan_; XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = ("\t"); System.IO.MemoryStream mStream = new System.IO.MemoryStream(); XmlWriter writer = XmlWriter.Create(mStream, settings); writer.WriteStartDocument(true); writer.WriteStartElement("PlanQualityReport"); writer.WriteAttributeString("created", DateTime.Now.ToString()); writer.WriteAttributeString("userid", currentuser); writer.WriteAttributeString("eclipseVersion", eclipseVersion); writer.WriteAttributeString("scriptVersion", scriptVersion); writer.WriteStartElement("Patient"); WritePatientXML(patient, writer); writer.WriteStartElement("PlanSum"); psum.WriteXml(writer); foreach (PlanSetup plan in psum.PlanSetups) { WritePlanXML(plan, writer, CtrlPtSelector.IncludeControlPoints); } writer.WriteEndElement(); // </PlanSum> writer.WriteEndElement(); // </Patient> writer.WriteStartElement("DoseStatistics"); WriteDoseStatisticsXML_Target(patient, ss, psum, writer); WriteDoseStatisticsXML_Prostate2GyOrLess(patient, ss, psum, writer); WriteDoseStatisticsXML_HeadAndNeck2GyOrLess(patient, ss, psum, writer); writer.WriteEndElement(); // </DoseStatistics> writer.WriteEndElement(); // </PlanQualityReport> writer.WriteEndDocument(); writer.Flush(); mStream.Flush(); // write the XML file report. using (System.IO.FileStream file = new System.IO.FileStream(sXMLPath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { // Have to rewind the MemoryStream in order to read its contents. mStream.Position = 0; mStream.CopyTo(file); file.Flush(); file.Close(); } writer.Close(); mStream.Close(); }
public void GetToolImage(ToolAdminModel toolAdm) { int offset = 0; TOOL_FAMILY toolfamily = new TOOL_FAMILY(); toolfamily = null; FileStream fileStream = null; byte[] photosource = null; System.IO.MemoryStream strm; try { toolfamily = (from c in DB.TOOL_FAMILY where c.FAMILY_CD == toolAdm.FAMILY_CD select c).SingleOrDefault <TOOL_FAMILY>(); if (toolfamily.IsNotNullOrEmpty()) { if (toolfamily.PICTURE != null) { photosource = toolfamily.PICTURE.ToArray(); offset = GetImageBytesFromOLEField(photosource, toolAdm); strm = new System.IO.MemoryStream(); strm.Write(photosource, offset, photosource.Length - offset); toolAdm.MimeType = getMimeFromFile(photosource); toolAdm.File_Name = System.AppDomain.CurrentDomain.BaseDirectory + "File" + toolfamily.FAMILY_CD + "." + toolAdm.FileType; if (toolAdm.FileType == "vsd") { toolAdm.DisplayFile_Name = System.AppDomain.CurrentDomain.BaseDirectory + "File" + toolfamily.FAMILY_CD + ".bmp"; } else { toolAdm.DisplayFile_Name = System.AppDomain.CurrentDomain.BaseDirectory + "File" + toolfamily.FAMILY_CD + "." + toolAdm.FileType; } //ToolAdm.File_Name = "E:\\File1.vsd"; fileStream = File.Create(toolAdm.File_Name); toolAdm.picture = strm; strm.Seek(0, SeekOrigin.Begin); strm.CopyTo(fileStream); fileStream.Close(); fileStream.Dispose(); strm.Close(); strm.Dispose(); } } } catch (System.Data.Linq.ChangeConflictException) { DB.ChangeConflicts.ResolveAll(System.Data.Linq.RefreshMode.KeepChanges); } catch (Exception ex) { throw ex.LogException(); } }
/// <summary> /// Exports the specified <see cref="TextDocument"/> to an external markdown file. /// </summary> /// <param name="document">The document to export.</param> /// <param name="fileName">Full name of the markdown file to export to.</param> public void Export(TextDocument document, string fileName) { var path = Path.GetDirectoryName(fileName); var imagePath = GetImagePath(path); var sourceDoc = new System.Text.StringBuilder(document.SourceText); var list = new List <(string Url, int urlSpanStart, int urlSpanEnd)>(document.ReferencedImageUrls); list.Sort((x, y) => Comparer <int> .Default.Compare(y.urlSpanEnd, x.urlSpanEnd)); // Note the inverse order of x and y to sort urlSpanEnd descending var imageStreamProvider = new ImageStreamProvider(); // Export images foreach (var(Url, urlSpanStart, urlSpanEnd) in list) { using (var stream = new System.IO.MemoryStream()) { var streamResult = imageStreamProvider.GetImageStream(stream, Url, 300, Altaxo.Main.ProjectFolder.GetFolderPart(document.Name), document.Images); if (streamResult.IsValid) { var hashName = MemoryStreamImageProxy.ComputeStreamHash(stream); var imageFileName = hashName + streamResult.Extension; if (!Directory.Exists(imagePath)) { Directory.CreateDirectory(imagePath); } // Copy stream to FileSystem using (var fileStream = new System.IO.FileStream(Path.Combine(imagePath, imageFileName), FileMode.Create, FileAccess.Write, FileShare.Read)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } // now change the url in the markdown text var newUrl = ImageDirectoryName + "/" + imageFileName; sourceDoc.Remove(urlSpanStart, 1 + urlSpanEnd - urlSpanStart); sourceDoc.Insert(urlSpanStart, newUrl); } } } // now save the markdown document using (var markdownStream = new System.IO.StreamWriter(fileName, false, Encoding.UTF8, 4096)) { markdownStream.Write(sourceDoc.ToString()); } }
public IActionResult Get() { List <string> fileName = new List <string>(); fileName.Add("00937dc9a02547cd95e17bf7f992f957.txt"); fileName.Add("025ce8e69d3640c498a653a43a0428dc.jpg"); List <SourceFile> sourceFiles = new List <SourceFile>(); foreach (var fname in fileName) { string[] fdata = fname.Split("."); CloudBlockBlob blockBlob = GetBlockBlobDetail(fname); Stream blobStream = blockBlob.OpenReadAsync().GetAwaiter().GetResult(); sourceFiles.Add(new SourceFile() { Name = fdata[0], Extension = fdata[1], FileBytes = ReadFully(blobStream) }); } // get the source files // ... // the output bytes of the zip byte[] fileBytes = null; // create a working memory stream using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // create a zip using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true)) { // interate through the source files foreach (SourceFile f in sourceFiles) { // add the item name to the zip System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(f.Name + "." + f.Extension); // add the item bytes to the zip entry by opening the original file and copying the bytes using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(f.FileBytes)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } fileBytes = memoryStream.ToArray(); } // download the constructed zip Response.Headers.Add("Content-Disposition", "attachment; filename=download.zip"); return(File(fileBytes, "application/zip")); }
public File SaveFile(File item, Directory directory) { IO.MemoryStream remoteStream = GetFileStream(item); string localFileUri = IO.Path.Combine(directory.GetUri().AbsolutePath, item.Name); IO.FileStream localStream = new IO.FileStream(localFileUri, IO.FileMode.Create, IO.FileAccess.Write); IO.StreamReader reader = new IO.StreamReader(remoteStream); IO.StreamWriter writer = new IO.StreamWriter(IO.Path.Combine(directory.GetUri().AbsolutePath, item.Name)); remoteStream.CopyTo(localStream); return(new File(localFileUri)); }
ExportImages(TextDocument document, string basePathName) { var imagePath = GetImagePath(basePathName); var list = new List <(string Url, int urlSpanStart, int urlSpanEnd)>(document.ReferencedImageUrls); list.Sort((x, y) => Comparer <int> .Default.Compare(y.urlSpanEnd, x.urlSpanEnd)); // Note the inverse order of x and y to sort urlSpanEnd descending var imageStreamProvider = new ImageStreamProvider(); var oldToNewImageUrl = new Dictionary <string, string>(); var listOfReferencedImageFileNames = new HashSet <string>(); // Export images foreach (var(Url, urlSpanStart, urlSpanEnd) in list) { using (var stream = new System.IO.MemoryStream()) { var streamResult = imageStreamProvider.GetImageStream(stream, Url, 300, Altaxo.Main.ProjectFolder.GetFolderPart(document.Name), document.Images); if (streamResult.IsValid) { var hashName = MemoryStreamImageProxy.ComputeStreamHash(stream); var imageFileName = hashName + streamResult.Extension; if (!Directory.Exists(imagePath)) { Directory.CreateDirectory(imagePath); } // Copy stream to FileSystem var fullImageFileName = Path.Combine(imagePath, imageFileName); using (var fileStream = new System.IO.FileStream(fullImageFileName, FileMode.Create, FileAccess.Write, FileShare.Read)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } // now change the url in the markdown text var newUrl = ImageFolderName + "/" + imageFileName; oldToNewImageUrl[Url] = newUrl; listOfReferencedImageFileNames.Add(fullImageFileName); } } } return(oldToNewImageUrl, listOfReferencedImageFileNames); }
public static byte[] ConvertAudio(byte[] sourceBytes) { using (System.IO.Stream sourceStream = new System.IO.MemoryStream(sourceBytes)) { using (System.IO.Stream destinationStream = new System.IO.MemoryStream()) { ConvertMp3ToWav(sourceStream, destinationStream); using (var memoryStream = new System.IO.MemoryStream()) { destinationStream.CopyTo(memoryStream); return(memoryStream.ToArray()); } } } }
public string DownloadPDF(string fileId, string fileName) { var request = service.Files.Export(fileId, "application/pdf"); var stream = new System.IO.MemoryStream(); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); string path = Path.GetTempPath(); Console.WriteLine(path); using (var fileStream = File.Create(path + fileName)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } return(path + fileName); }
public void TestEncode() { var input = GetBytes("TestBrotli.Resource.BingCN.bin"); Byte[] output = null; using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(input)) using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) using (BrotliStream bs = new BrotliStream(msOutput, System.IO.Compression.CompressionMode.Compress)) { bs.SetQuality(11); bs.SetWindow(22); msInput.CopyTo(bs); bs.Close(); output = msOutput.ToArray(); Boolean eq = ArrayEqual(output, GetBytes("TestBrotli.Resource.BingCN_Compressed.bin")); Assert.True(eq); } }
public void TestEncode() { var input = System.Text.Encoding.UTF8.GetBytes(TestResource.BingCN); Byte[] output = null; using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(input)) using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) using (BrotliStream bs = new BrotliStream(msOutput, System.IO.Compression.CompressionMode.Compress)) { bs.SetQuality(11); bs.SetWindow(22); msInput.CopyTo(bs); bs.Close(); output = msOutput.ToArray(); Boolean eq = ArrayEqual(output, TestResource.BingCN_Compressed); Assert.AreEqual(true, eq); } }
/// <summary> /// 指定したファイルを復号化し、データに出力します。 /// </summary> /// <param name="filepath">復号化したいファイルの名前</param> /// <param name="ms">データを格納するためのメモリストリーム</param> /// <returns></returns> public static void DecryptionFile(string filepath, MemoryStream ms) { using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.BlockSize = 128; //ブロックサイズ(128bit) aes.KeySize = 128; //キー最大長(128bit) aes.Mode = CipherMode.CBC; //CBCモード aes.Padding = PaddingMode.PKCS7; //パディングモード byte[] bytesIV = new byte[16]; aes.Key = AESTransformBytes(PASSWORD); //キーの設定 //暗号化データを読み込んでいく using (System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { //IVを先頭から取り出してAesCryptoServiceProviderオブジェクトにセット fs.Read(bytesIV, 0, 16); aes.IV = bytesIV; //AES 復号オブジェクトの作成 ICryptoTransform encrypt = aes.CreateDecryptor(); //仮MemoryStreamの生成 using (System.IO.MemoryStream ms_tmp = new System.IO.MemoryStream()) { //CryptoStreamの作成 CryptoStream cs = new CryptoStream( ms_tmp, encrypt, CryptoStreamMode.Write); //データの書き込み byte[] buffer = new byte[1024]; int len; while ((len = fs.Read(buffer, 0, buffer.Length)) > 0) { cs.Write(buffer, 0, len); } ms_tmp.Seek(0, SeekOrigin.Begin); //位置を初期化 ms_tmp.CopyTo(ms); //コピー ms.Seek(0, SeekOrigin.Begin); //位置を初期化 } } } }
private void DownloadFile(string fileId, string dest) { logger.Debug("file downloading...{0}", fileId); Google.Apis.Drive.v3.FilesResource.GetRequest request = service.Files.Get(fileId); var stream = new System.IO.MemoryStream(); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { logger.Debug(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { logger.Debug("Download complete."); break; } case DownloadStatus.Failed: { logger.Debug("Download failed."); break; } } }; request.Download(stream); using (var fileStream = System.IO.File.Create(dest)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } logger.Debug("file downloaded:{0}", dest); }
public static void DownloadFile(Google.Apis.Drive.v3.Data.File file, DriveService driveService, string path) { var fileId = file.Id;//"0BwwA4oUTeiV1UVNwOHItT0xfa2M"; var request = driveService.Files.Get(fileId); var stream = new System.IO.MemoryStream(); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded / 1024 + " Kbytes downloaded"); break; } case DownloadStatus.Completed: { using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { stream.Flush(); stream.Position = 0; stream.CopyTo(fileStream); } stream.Close(); Console.WriteLine("Download complete."); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); }
public static byte[] decodeMP3ToWavMono(byte[] sourceBytes) { using (System.IO.Stream sourceStream = new System.IO.MemoryStream(sourceBytes)) { using (var destinationStream = new System.IO.MemoryStream()) { using (var tempStream = new System.IO.MemoryStream()) { using (MP3Sharp.MP3Stream stream = new MP3Sharp.MP3Stream(sourceStream, 4096, MP3Sharp.SoundFormat.Pcm16BitMono)) { stream.CopyTo(tempStream); WriteWavHeader(destinationStream, false, (ushort)1, 16, stream.Frequency, tempStream.Length); tempStream.Seek(0, SeekOrigin.Begin); tempStream.CopyTo(destinationStream); return(destinationStream.ToArray()); } } } } }
// // GET: /Home/Icon/{id} public ActionResult Icon(string id /*fileName*/) { var fileName = id; string path = HttpContext.Server.MapPath(filesDir + fileName); using (Stream fileStream = System.IO.File.OpenRead(path)) { using (var output = new System.IO.MemoryStream()) { FileService.AdjustImageToHeight(fileStream, output, 100); this.Response.ContentType = "image/jpeg"; this.Response.AddHeader("Content-Length", output.Length.ToString()); this.Response.Cache.SetExpires(DateTime.Now /*.AddDays(30)*/); this.Response.Cache.SetCacheability(HttpCacheability.NoCache /*Private*/); this.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); output.CopyTo(this.Response.OutputStream); } } return(new EmptyResult()); }
internal static string CompressToBase64String(this List <OutEntity> unsyncdRecs) { var js = Newtonsoft.Json.JsonConvert.SerializeObject(unsyncdRecs); var bytes = System.Text.Encoding.UTF8.GetBytes(js); var b64 = string.Empty; using (var input = new System.IO.MemoryStream(bytes)) { using (var outStream = new System.IO.MemoryStream()) using (var deflateStream = new System.IO.Compression .DeflateStream(outStream, System.IO.Compression.CompressionMode.Compress)) { input.CopyTo(deflateStream); deflateStream.Close(); b64 = System.Convert.ToBase64String(outStream.ToArray()); } } return(b64); }
private static HttpContent CompressRequestContent(string content) { var compressedStream = new MemoryStream(); using (var contentStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(content))) { using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress)) { contentStream.CopyTo(gzipStream); } } var byteArray = compressedStream.ToArray(); Logger.Debug("byte array size: " + byteArray.Length); var httpContent = new ByteArrayContent(byteArray); httpContent.Headers.Add("Content-encoding", "gzip"); httpContent.Headers.Add("Content-type", "application/gzip"); return(httpContent); }
private System.IO.Stream MessageToStream(Message message, HttpContextServiceHost ctx) { System.IO.Stream ms = new System.IO.MemoryStream(); using (System.IO.Stream tempms = new System.IO.MemoryStream()) { using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(tempms)) { message.WriteMessage(writer); writer.Flush(); } ctx.OriginalContentLength = (int)tempms.Length; tempms.Position = 0; /* * using (System.IO.FileStream fs = new FileStream(@"d:\f1.xml", FileMode.CreateNew)) * { * tempms.CopyTo(fs); * fs.Flush(); * } * tempms.Position = 0; */ using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { tempms.CopyTo(gzip); } } ms.Position = 0; /* * using (System.IO.FileStream fs = new FileStream(@"d:\f2.xml.zip", FileMode.CreateNew)) * { * ms.CopyTo(fs); * fs.Flush(); * } * ms.Position = 0; */ return(ms); }
private System.IO.Stream MessageToStream(HttpContextServiceHost ctx, Message message) { System.IO.Stream ms = new System.IO.MemoryStream(); using (System.IO.Stream tempms = new System.IO.MemoryStream()) { using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(tempms)) { message.WriteMessage(writer); writer.Flush(); } ctx.OriginalContentLength = (int)tempms.Length; tempms.Position = 0; using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { tempms.CopyTo(gzip); } } ms.Position = 0; return(ms); }
public IActionResult Download() { IList <Anexo> sourceFiles = AnexoRepository.anexos; // ... // the output bytes of the zip byte[] fileBytes = null; // create a working memory stream using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // create a zip using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true)) { // interate through the source files foreach (var f in sourceFiles) { // add the item name to the zip System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(f.Name); // add the item bytes to the zip entry by opening the original file and copying the bytes using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(f.file)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } fileBytes = memoryStream.ToArray(); } // download the constructed zip Response.Headers.Add("Content-Disposition", "attachment; filename=download.zip"); // .("Content-Disposition", "attachment; filename=download.zip"); return(File(fileBytes, "application/zip")); }
private async Task <FileInfo> DownloadAssetAsync(Dictionary <string, object> assetInfo) { try { FileInfo fileInfo = null; var path = Path.Combine(_settings.DownloadDirPath, Path.GetFileName(assetInfo["name"].ToString())); HttpClient.DefaultRequestHeaders.Accept.First().MediaType = assetInfo["content_type"].ToString(); using (var response = await HttpClient.GetAsync(new Uri(assetInfo["url"].ToString())).ConfigureAwait(IsConfigureAwait)) { var jObject = await response.Content.ReadAsByteArrayAsync(); System.IO.MemoryStream stream = new System.IO.MemoryStream(jObject); // convert stream to string StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); using (var fileStream = File.Create(path)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); fileInfo = new FileInfo(path); } } return(fileInfo); } catch (Exception ex) { Console.WriteLine(ex.Message + " | " + ex.StackTrace); throw new Exception("Release assets download failed."); } finally { HttpClient.DefaultRequestHeaders.Accept.First().MediaType = "application/vnd.github.v3.raw"; } }
static void Main(string[] args) { List <Person> persons = new List <Person>(); persons.Add(new Person { Name = "dalong", Age = 18 }); persons.Add(new Person { Name = "ava", Age = 17 }); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) using (StreamWriter writer = new StreamWriter(ms)) using (FileStream fs = File.OpenWrite(@"c:\temp\1.txt")) { foreach (var p in persons) { writer.WriteLine(p.Name + ":" + p.Age); } writer.Flush(); ms.Position = 0; ms.CopyTo(fs); } }
private byte[] writeContentToZip(List <PDFStream> pdfStreams, NBElement outputRoot) { byte[] zipContent = null; List <String> fileNames = new List <String>(); try { using (var outStream = new MemoryStream()) { using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true)) { foreach (PDFStream pdfs in pdfStreams) { if (fileNames.Where(fn => fn == pdfs.fileName).Count() == 0) { fileNames.Add(pdfs.fileName); ZipArchiveEntry zipItem = archive.CreateEntry(pdfs.fileName); using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(pdfs.stream)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } } zipContent = outStream.ToArray(); } } catch (Exception e) { handleError("PDF10003", e, outputRoot, "Error writing content to zip file"); } return(zipContent); }
public ActionResult DownloadAttachments(string data) { Download model = JsonConvert.DeserializeObject <Download>(data); CreateZip.DirectoriesFiles sfiles = new CreateZip.DirectoriesFiles { Files = new List <CreateZip.FileInfo>(), Folder = new List <CreateZip.Folder>() }; try { if (Convert.ToString(Session["PAT"]) != null) { string token = Convert.ToString(Session["PAT"]); CLWorkItem cLWorkItem = new CLWorkItem(token); // the output bytes of the zip byte[] fileBytes = null; if (model.ExportType == "File") { foreach (var wi in model.DocumentIds) { CreateZip.FileInfo fileInfo = new CreateZip.FileInfo(); fileInfo.FileBytes = cLWorkItem.DownloadAttachment(model.AccountName, model.ProjectName, wi.DocId, wi.DocName); String docName = wi.DocName; int index = docName.LastIndexOf("."); String documentName = docName.Substring(0, index); String documentExtension = docName.Substring(index + 1); fileInfo.Name = wi.WorkItemId + "__" + documentName; fileInfo.Extension = documentExtension; sfiles.Files.Add(fileInfo); } //create a working memory stream using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // create a zip using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true)) { if (sfiles.Files != null && sfiles.Files.Count > 0) { foreach (var outerFile in sfiles.Files) { // add the item name to the zip System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(outerFile.Name + "." + outerFile.Extension); // add the item bytes to the zip entry by opening the original file and copying the bytes using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(outerFile.FileBytes)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } } fileBytes = memoryStream.ToArray(); } } else { CreateZip.Folder folder = new CreateZip.Folder(); foreach (var wi in model.DocumentIds) { CreateZip.Folder folderq = new CreateZip.Folder(); folderq.FolderItems = new List <CreateZip.FolderItem>(); CreateZip.FolderItem folderItem = new CreateZip.FolderItem(); folderq.FolderName = wi.WorkItemId; String fDocName = wi.DocName; int fIndex = fDocName.LastIndexOf("."); String folderItemName = fDocName.Substring(0, fIndex); String folderItemExtension = fDocName.Substring(fIndex + 1); folderItem.Name = folderItemName; folderItem.Extension = folderItemExtension; folderItem.FileBytes = cLWorkItem.DownloadAttachment(model.AccountName, model.ProjectName, wi.DocId, wi.DocName); folderq.FolderItems.Add(folderItem); sfiles.Folder.Add(folderq); } using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // create a zip using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true)) { if (sfiles.Folder != null && sfiles.Folder.Count > 0) { foreach (var fldr in sfiles.Folder) { // add the item name to the zip // each file in the folder foreach (var file in fldr.FolderItems) { // add the item name to the zip System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(fldr.FolderName + "/" + file.Name + "." + file.Extension); // add the item bytes to the zip entry by opening the original file and copying the bytes using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(file.FileBytes)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } } } fileBytes = memoryStream.ToArray(); } } // download the constructed zip Response.AddHeader("Content-Disposition", "attachment; filename=" + "WIAttachments_" + model.ProjectName + ".zip"); return(File(fileBytes, "application/zip")); } else { return(RedirectToAction("../Account/Verify")); } } catch (Exception ex) { logger.Append(ex.Message); logger.Append(ex.StackTrace); return(RedirectToAction("../Account/Verify")); } }
private void DownloadAll() { try { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; var request = service.Files.List(); request.Spaces = "appDataFolder"; request.Fields = "nextPageToken, files(id, name)"; request.PageSize = 10; var result = request.Execute(); var driveFiles = result.Files.ToList(); Directory.CreateDirectory("Budgets"); var localFiles = Directory.EnumerateFiles(_path, "*.sqlite").ToList(); foreach (var file in localFiles) { var fileName = Path.GetFileName(file); if (driveFiles.Any(x => x.Name.Equals(fileName) && File.GetLastWriteTime(file) < x.ModifiedTime)) { //DOWNLOAD NEW VERSION TO PC Dispatcher.Invoke((Action)(() => { _budgetList.Add(new Budget(fileName, Path.GetFullPath(file), Path.GetFileNameWithoutExtension(file))); var budget = _budgetList.First(x => x.Name.Equals(fileName)); budget.LoadAble = false; budget.State = "Updating"; ListViewBudgets.ItemsSource = _budgetList; ListViewBudgets.Items.Refresh(); })); var fileId = driveFiles.First(x => x.Name.Equals(Path.GetFileName(file))).Id; var downloadRequest = service.Files.Get(fileId); var stream = new MemoryStream(); downloadRequest.Download(stream); var downloadPath = Path.Combine(_path, Path2.GetFileName(file)); stream.Position = 0; var fileStream = File.Create(downloadPath); stream.CopyTo(fileStream); fileStream.Close(); Dispatcher.Invoke(() => { var budget = _budgetList.First(x => x.Name.Equals(fileName)); budget.LoadAble = true; budget.State = "Ready"; ListViewBudgets.ItemsSource = _budgetList; ListViewBudgets.Items.Refresh(); }); } } foreach (var file in driveFiles) { if (!localFiles.Any(x => Path.GetFileName(x).Equals(file.Name))) { //DOWNLOAD NEW BUDGET TO PC this.Dispatcher.Invoke((Action)(() => { string noExtension = file.Name; string[] a = noExtension.Split('.'); noExtension = a[0]; _budgetList.Add(new Budget(file.Name, "", noExtension)); var budget = _budgetList.First(x => x.Name.Equals(file.Name)); budget.LoadAble = false; budget.State = "Downloading"; ListViewBudgets.ItemsSource = _budgetList; ListViewBudgets.Items.Refresh(); })); var fileId = file.Id; var downloadRequest = service.Files.Get(fileId); var stream = new System.IO.MemoryStream(); downloadRequest.Download(stream); var downloadPath = Path.Combine(_path, file.Name); stream.Position = 0; var fileStream = File.Create(downloadPath); stream.CopyTo(fileStream); fileStream.Close(); this.Dispatcher.Invoke((Action)(() => { var budget = _budgetList.First(x => x.Name.Equals(file.Name)); budget.Path = Path.GetFullPath(downloadPath); budget.NameWithoutExtension = Path.GetFileNameWithoutExtension(downloadPath); budget.LoadAble = false; budget.State = "Ready"; ListViewBudgets.ItemsSource = _budgetList; ListViewBudgets.Items.Refresh(); })); } } } catch (Exception exception) when(exception is Google.GoogleApiException || exception is HttpRequestException) { bool retry = false; Dispatcher.Invoke((Action)(() => { YesNo yesNo = new YesNo("Quickbudget failed to connect to Google Drive. Do you want to try again?") { Owner = GetWindow(this) }; yesNo.ShowDialog(); if (yesNo.IsSuccesful) { retry = true; } })); if (retry) { DownloadAll(); } else { //TODO load local } } }
public ActionResult ZipAndDownloadFiles(string fileName) { string filePath = Server.MapPath("~") + @"ExtractedTemplate\" + fileName; try { CreateZips.SourceDirectoriesFiles sfiles = new CreateZips.SourceDirectoriesFiles(); if (System.IO.Directory.Exists(filePath)) { string[] files = Directory.GetFiles(filePath); string[] subDirs = Directory.GetDirectories(filePath); if (files.Length > 0) { sfiles.Files = new List <CreateZips.FileInfo>(); foreach (var f in files) { CreateZips.FileInfo fileInfo = new CreateZips.FileInfo(); string[] fSplit = f.Split('\\'); string splitLength = fSplit[fSplit.Length - 1]; fSplit = splitLength.Split('.'); fileInfo.Name = fSplit[0]; fileInfo.Extension = fSplit[1]; fileInfo.FileBytes = System.IO.File.ReadAllBytes(f); sfiles.Files.Add(fileInfo); } } if (subDirs.Length > 0) { sfiles.Folder = new List <CreateZips.Folder>(); foreach (var dir in subDirs) { string[] subDirFiles = System.IO.Directory.GetFiles(dir); string[] subDirsLevel2 = Directory.GetDirectories(dir); if (subDirFiles.Length > 0) { CreateZips.Folder folder = new CreateZips.Folder(); string[] getFolderName = dir.Split('\\'); string subFolderName = getFolderName[getFolderName.Length - 1]; folder.FolderName = subFolderName; folder.FolderItems = new List <CreateZips.FolderItem>(); foreach (var sdf in subDirFiles) { CreateZips.FolderItem folderItem = new CreateZips.FolderItem(); string[] fSplit = sdf.Split('\\'); string splitLength = fSplit[fSplit.Length - 1]; fSplit = splitLength.Split('.'); folderItem.Name = fSplit[0]; folderItem.Extension = fSplit[1]; folderItem.FileBytes = System.IO.File.ReadAllBytes(sdf); folder.FolderItems.Add(folderItem); } if (subDirsLevel2.Length > 0) { folder.FolderL2 = new List <CreateZips.FolderL2>(); foreach (var dirL2 in subDirsLevel2) { string[] subDirFilesL2 = System.IO.Directory.GetFiles(dirL2); if (subDirFilesL2.Length > 0) { CreateZips.FolderL2 folderFL2 = new CreateZips.FolderL2(); string[] getFolderNameL2 = dirL2.Split('\\'); string subFolderNameL2 = getFolderNameL2[getFolderNameL2.Length - 1]; folderFL2.FolderName = subFolderNameL2; folderFL2.FolderItems = new List <CreateZips.FolderItem>(); foreach (var sdfL2 in subDirFilesL2) { CreateZips.FolderItem folderItem = new CreateZips.FolderItem(); string[] fSplit = sdfL2.Split('\\'); string splitLength = fSplit[fSplit.Length - 1]; fSplit = splitLength.Split('.'); folderItem.Name = fSplit[0]; folderItem.Extension = fSplit[1]; folderItem.FileBytes = System.IO.File.ReadAllBytes(sdfL2); folderFL2.FolderItems.Add(folderItem); } folder.FolderL2.Add(folderFL2); } } } sfiles.Folder.Add(folder); } } } } // ... // the output bytes of the zip byte[] fileBytes = null; //create a working memory stream using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // create a zip using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true)) { // interate through the source files if (sfiles.Folder != null && sfiles.Folder.Count > 0) { //each folder in source file [depth 1] foreach (var folder in sfiles.Folder) { // add the item name to the zip // each file in the folder foreach (var file in folder.FolderItems) { // folder items - file name, extension, and file bytes or content in bytes // zip.CreateEntry can create folder or the file. If you just provide a name, it will create a folder (if it doesn't not exist). If you provide with extension, it will create file System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(folder.FolderName + "/" + file.Name + "." + file.Extension); // Creating folder and create file inside that folder using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(file.FileBytes)) // adding file bytes to memory stream object { using (System.IO.Stream entryStream = zipItem.Open()) // opening the folder/file { originalFileMemoryStream.CopyTo(entryStream); // copy memory stream dat bytes to file created } } // for second level of folder like /Template/Teams/BoardColums.json //each folder in source file [depth 2] if (folder.FolderL2 != null && folder.FolderL2.Count > 0) { foreach (var folder2 in folder.FolderL2) { foreach (var file2 in folder2.FolderItems) { System.IO.Compression.ZipArchiveEntry zipItem2 = zip.CreateEntry(folder.FolderName + "/" + folder2.FolderName + "/" + file2.Name + "." + file2.Extension); using (System.IO.MemoryStream originalFileMemoryStreamL2 = new System.IO.MemoryStream(file2.FileBytes)) { using (System.IO.Stream entryStreamL2 = zipItem2.Open()) { originalFileMemoryStreamL2.CopyTo(entryStreamL2); } } } } } } } } if (sfiles.Files != null && sfiles.Files.Count > 0) { foreach (var outerFile in sfiles.Files) { // add the item name to the zip System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(outerFile.Name + "." + outerFile.Extension); // add the item bytes to the zip entry by opening the original file and copying the bytes using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(outerFile.FileBytes)) { using (System.IO.Stream entryStream = zipItem.Open()) { originalFileMemoryStream.CopyTo(entryStream); } } } } } fileBytes = memoryStream.ToArray(); } // download the constructed zip Directory.Delete(filePath, true); Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip"); return(File(fileBytes, "application/zip")); } catch (Exception ex) { ExtractorService.logger.Info(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + ex.Message + "\n" + ex.StackTrace + "\n"); } finally { if (Directory.Exists(filePath)) { Directory.Delete(filePath, true); } } ViewBag.Error = "File not found"; return(RedirectToAction("Index", "Extractor")); }
protected void Page_Load(object sender, EventArgs e) { string domain = "http://localhost:2779/"; string qrCodeImgFileName = new Random().Next().ToString() + ".jpg"; // QR Code information == QR Code validation url string qrCodeInformation = domain + "ValidateQR.aspx?identity=" + qrCodeImgFileName; // Generate QR Code QRCodeEncoder qe = new QRCodeEncoder(); System.Drawing.Bitmap bm = qe.Encode(qrCodeInformation); // Save QR Code bitmap to memory stream var memStream = new MemoryStream(); bm.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg); // Save Jpeg stream into file using (var fileStream = new FileStream(Server.MapPath("~/QRCodes/") + qrCodeImgFileName, FileMode.CreateNew, FileAccess.ReadWrite)) { memStream.Position = 0; memStream.CopyTo(fileStream); } // View generated QR Code // Download free QR Scanner mobile application and scan using mobile, you will see http://localhost:2779/ValidateQR.aspx?identity=some_random as result Image1.ImageUrl = "~/QRCodes/" + qrCodeImgFileName; Label1.Text = qrCodeInformation; }