当前位置: 首页>>代码示例>>C#>>正文


C# MemoryStream.Dispose方法代码示例

本文整理汇总了C#中System.IO.MemoryStream.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryStream.Dispose方法的具体用法?C# MemoryStream.Dispose怎么用?C# MemoryStream.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.MemoryStream的用法示例。


在下文中一共展示了MemoryStream.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Draw

        public virtual IDisposable Draw(DrawingContext drawingContext, Rect targetItemRect, int level)
        {
            //Default is to draw the image bits into the context:

            //Do not dispose of the memory stream here, because System.Media.Windows uses
            // retained mode rendering where the commands get batched to execute later.
            MemoryStream imageStream = new MemoryStream(this.ImageData);
            try
            {
                TransformedBitmap shrunkImage = ResizePng(imageStream, targetItemRect.Size);

                //DrawingContext.DrawImage will scale an image to fill the size, so modify
                // our target rect to be exactly the correct image position on the tile.
                Rect targetImageRect = new Rect(targetItemRect.X, targetItemRect.Y,
                    shrunkImage.PixelWidth, shrunkImage.PixelHeight);
                drawingContext.DrawImage(shrunkImage, targetImageRect);

                return imageStream; //Return our stream so it can be disposed later.
            }
            catch
            {
                if (null != imageStream)
                {
                    imageStream.Dispose();
                }
                throw;
            }
        }
开发者ID:JuliettAlex,项目名称:Sales,代码行数:28,代码来源:ImageProviderBase.cs

示例2: MemoryImage

        /// <exception cref="InvalidImageException">
        /// ストリームから読みだされる画像データが不正な場合にスローされる
        /// </exception>
        protected MemoryImage(MemoryStream stream)
        {
            try
            {
                this.Image = Image.FromStream(stream);
            }
            catch (ArgumentException e)
            {
                stream.Dispose();
                throw new InvalidImageException("Invalid image", e);
            }
            catch (OutOfMemoryException e)
            {
                // GDI+ がサポートしない画像形式で OutOfMemoryException がスローされる場合があるらしい
                stream.Dispose();
                throw new InvalidImageException("Invalid image?", e);
            }
            catch (ExternalException e)
            {
                // 「GDI+ で汎用エラーが発生しました」という大雑把な例外がスローされる場合があるらしい
                stream.Dispose();
                throw new InvalidImageException("Invalid image?", e);
            }
            catch (Exception)
            {
                stream.Dispose();
                throw;
            }

            this.Stream = stream;
        }
开发者ID:betarium,项目名称:OpenTweenXP,代码行数:34,代码来源:MemoryImage.cs

示例3: SendPacket

        public async Task SendPacket(IPacket packet, Stream netStream)
        {
            var ms = new MemoryStream();
            var bw = new BinaryWriter(ms);

            if (packet is IAutoSerializePacket)
                (packet as IAutoSerializePacket).AutoSerialize(bw);
            else
            {
                bw.Write(packet.ID);
                packet.SerializePacket(bw);
            }

            bw.Flush();

            // Copy ms -> redirect writer to new ms -> prepend packet size prefix -> append packet paylod
            FinalizePacket(ref bw);
            ms.Dispose(); // Dispose of expired ms, writer's basestream is created in FinalizePacket
            ms = bw.BaseStream as MemoryStream;
            // this here failed? ye wait a moment
            await netStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length);

            if (OnPacketSent != null)
                OnPacketSent(null, new PacketEventArgs(null, packet, (int)ms.Length));

            ms.Dispose();
            bw.Dispose();

        }
开发者ID:Numbers11,项目名称:uNet,代码行数:29,代码来源:PacketProcessor.cs

示例4: GetFileAsync

        public async Task<Stream> GetFileAsync(string folderName, string fileName)
        {
            if (String.IsNullOrWhiteSpace(folderName))
            {
                throw new ArgumentNullException("folderName");
            }

            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            ICloudBlobContainer container = await GetContainer(folderName);

            var blob = container.GetBlobReference(fileName);

            var stream = new MemoryStream();
            try
            {
                await blob.DownloadToStreamAsync(stream);
            }
            catch (StorageException ex)
            {
                stream.Dispose();

                if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.BlobNotFound)
                {
                    return null;
                }

                throw;
            }
            catch (TestableStorageClientException ex)
            {
                // This is for unit test only, because we can't construct an 
                // StorageException object with the required ErrorCode
                stream.Dispose();

                if (ex.ErrorCode == BlobErrorCodeStrings.BlobNotFound)
                {
                    return null;
                }

                throw;
            }

            stream.Position = 0;
            return stream;
        }
开发者ID:bnicoloff,项目名称:NuGetGallery,代码行数:49,代码来源:CloudBlobFileStorageService.cs

示例5: ProcessEMF

 public void ProcessEMF(byte[] emf)
 {
     try
     {
         _ms = new MemoryStream(emf);
         _mf = new Metafile(_ms);
         _bm = new Bitmap(1, 1);
         g = Graphics.FromImage(_bm);
         //XScale = Width / _mf.Width;
         //YScale = Height/ _mf.Height;
         m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback);
         g.EnumerateMetafile(_mf, new Point(0, 0), m_delegate);
     }
     finally
     {
         if (g != null)
             g.Dispose();
         if (_bm != null)
             _bm.Dispose();
         if (_ms != null)
         {
             _ms.Close();
             _ms.Dispose();
         }
     }
 }
开发者ID:NelsonSantos,项目名称:fyiReporting-Android,代码行数:26,代码来源:EMF.cs

示例6: BitmapImageFromBytes

 private BitmapImage BitmapImageFromBytes(byte[] bytes)
 {
     BitmapImage image = null;
     MemoryStream stream = null;
     try
     {
         stream = new MemoryStream(bytes);
         stream.Seek(0, SeekOrigin.Begin);
         System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
         image = new BitmapImage();
         image.BeginInit();
         MemoryStream ms = new MemoryStream();
         img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
         ms.Seek(0, SeekOrigin.Begin);
         image.StreamSource = ms;
         image.StreamSource.Seek(0, SeekOrigin.Begin);
         image.EndInit();
     }
     catch (Exception)
     {
         throw;
     }
     finally
     {
         stream.Close();
         stream.Dispose();
     }
     return image;
 }
开发者ID:devalacarte,项目名称:kassysteem_nmct,代码行数:29,代码来源:StringToImageConverter.cs

示例7: StreamWriteAsyncTest

        public async Task StreamWriteAsyncTest()
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            MemoryStream stream1 = new MemoryStream(buffer);
            MemoryStream stream2 = new MemoryStream();

            OperationContext tempOperationContext = new OperationContext();
            RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null);
            ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext);

            // Test basic write
            await stream1.WriteToAsync(stream2, null, null, false, tempExecutionState, null, CancellationToken.None);
            stream1.Position = 0;

            TestHelper.AssertStreamsAreEqual(stream1, stream2);

            stream2.Dispose();
            stream2 = new MemoryStream();

            await TestHelper.ExpectedExceptionAsync<ArgumentException>(
                async () => await stream1.WriteToAsync(stream2, 1024, 1024, false, tempExecutionState, null, CancellationToken.None),
                "Parameters copyLength and maxLength cannot be passed simultaneously.");

            stream1.Dispose();
            stream2.Dispose();
        }
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:26,代码来源:WriteToAsyncTests.cs

示例8: Image

 /// <summary>
 /// Creates an image object from bytes.
 /// </summary>
 /// <param name="stream">Stream of bytes</param>
 public Image(MemoryStream stream) {
     if (stream == null || stream.Length == 0)
         throw new Errors.NullImageError();
     _bitmap = (Bitmap)Bitmap.FromStream(stream, false, false);
     stream.Dispose();
     COMDisposable.Subscribe(this, typeof(ComInterfaces._Image));
 }
开发者ID:thomb1,项目名称:SeleniumBasic,代码行数:11,代码来源:Image.cs

示例9: CreateThumbnail

        public static byte[] CreateThumbnail(byte[] imageByte, bool maintainAspectRatio, int desiredWidth, int desiredHeight)
        {
            byte[] byteArray = new byte[0];
            Bitmap bmp;
            try
            {
                MemoryStream memStream = new MemoryStream(imageByte);
                System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

                if (maintainAspectRatio)
                {
                    AspectRatio aspectRatio = new AspectRatio();
                    aspectRatio.WidthAndHeight(img.Width, img.Height, desiredWidth, desiredHeight);
                    bmp = new Bitmap(img, aspectRatio.Width, aspectRatio.Height);
                }
                else
                {
                    bmp = new Bitmap(img, desiredWidth, desiredHeight);
                }
                byteArray = ToByteArray(bmp, ImageFormat.Jpeg);
                memStream.Dispose();
            }
            catch (Exception ex)
            {

            }
            return byteArray;
        }
开发者ID:devmicrominds,项目名称:HIS-Project,代码行数:28,代码来源:ImageHelper.cs

示例10: SingleLineSummary

        public void SingleLineSummary()
        {
            // Given
            string code = @"
                namespace Foo
                {
                    /// <summary>This is a summary.</summary>
                    class Green
                    {
                    }

                    /// <summary>This is another summary.</summary>
                    struct Red
                    {
                    }
                }
            ";
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(code));
            IDocument document = Substitute.For<IDocument>();
            document.GetStream().Returns(stream);
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.InputFolder.Returns(Environment.CurrentDirectory);
            context.GetNewDocument(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<IEnumerable<MetadataItem>>())
                .Returns(x => new TestDocument((IEnumerable<MetadataItem>)x[2]));
            IModule module = new AnalyzeCSharp();

            // When
            List<IDocument> results = module.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            // Then
            Assert.AreEqual("This is a summary.", GetResult(results, "Green")["Summary"]);
            Assert.AreEqual("This is another summary.", GetResult(results, "Red")["Summary"]);
            stream.Dispose();
        }
开发者ID:martinvobr,项目名称:Wyam,代码行数:34,代码来源:AnalyzeCSharpXmlDocumentationFixture.cs

示例11: ParallelNewVsGet

		public void ParallelNewVsGet()
		{
			var manager = new MemoryStreamManager(memoryBlockSize);

			var newResults = LoadTest.ExecuteParallelAsync
				(
					"new",
					index =>
					{
						var stream = new MemoryStream(memoryBlockSize);

						stream.Dispose();
					},
					iterationCount,
					4096
				).Result;

			Trace.Write(newResults.ToString());

			var cacheResults = LoadTest.ExecuteParallelAsync
				(
					"get",
					index =>
					{
						var stream = manager.Get();

						manager.Put(stream);
					},
					iterationCount,
					4096
				).Result;

			Trace.Write(cacheResults.ToString());
		}
开发者ID:stas-sultanov,项目名称:SXN.Core,代码行数:34,代码来源:MemoryStreamManagerTests.cs

示例12: GetVsNew

		public void GetVsNew()
		{
			var manager = new MemoryStreamManager(memoryBlockSize);

			var results = LoadTest.ExecuteCompare
				(
					"Get",
					index =>
					{
						var stream = manager.Get();

						manager.Put(stream);
					},
					"New",
					index =>
					{
						var stream = new MemoryStream(memoryBlockSize);

						stream.Dispose();
					},
					iterationCount
				);

			Trace.Write(results.ToString());
		}
开发者ID:stas-sultanov,项目名称:SXN.Core,代码行数:25,代码来源:MemoryStreamManagerTests.cs

示例13: ReadFromStreamWithDefaultColumnsShouldHandleFirstRowAsRowData

        public void ReadFromStreamWithDefaultColumnsShouldHandleFirstRowAsRowData()
        {
            DataTableBuilder builder = new DataTableBuilder();
            var stream = new MemoryStream();
            var sw = new StreamWriter(stream);
            var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", };
            foreach (var row in rows)
            {
                sw.WriteLine(row);
            }

            sw.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            try
            {
                var lazy = builder.ReadLazy(stream, rows[0].Split(','));
                Assert.Equal(rows[0].Split(','), lazy.ColumnNames);
                var rowEnumerator = rows.Skip(0).GetEnumerator();
                rowEnumerator.MoveNext();
                var rowCount = 0;
                foreach (var row in lazy.Rows)
                {
                    Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values));
                    rowEnumerator.MoveNext();
                    rowCount++;
                }

                Assert.Equal(rows.Length, rowCount);
            }
            finally
            {
                sw.Dispose();
                stream.Dispose();
            }
        }
开发者ID:aaronhoffman,项目名称:DataTable,代码行数:35,代码来源:ReaderTests.cs

示例14: ProcessBitmap

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override Image ProcessBitmap()
        {
            if (Opetion == null) throw new ImageException("Opetion is null");
            if (TextFont == null) TextFont = new Font("SimSun", 20);
            MemoryStream sourcestream = new MemoryStream(SourceImgBuffter);

            var sourceImg = Image.FromStream(sourcestream);

            var trageSize = Opetion == null ? null : Opetion.TragetSize;
            Image tmpimg = trageSize != null ? new Bitmap(trageSize.Value.Width, trageSize.Value.Height) : new Bitmap(sourceImg.Width, sourceImg.Height);
            Graphics gType = CreateGraphics(tmpimg, sourceImg);
            var attributes = GetOpacity(Opetion.Opacity);
            var sizef = gType.MeasureString(Text, TextFont, sourceImg.Width, StringFormat.GenericDefault);
            var waterImg = new Bitmap((int)sizef.Width, (int)sizef.Height);
            var waterRectangle = GetWaterRectangle(sourceImg, waterImg);
            var tmpwatrer = CreateFillImage(waterImg);
            try
            {
                gType.DrawImage(tmpwatrer, waterRectangle, 0, 0, tmpwatrer.Width, tmpwatrer.Height, GraphicsUnit.Pixel, attributes);
                return tmpimg;
            }
            finally
            {
                sourcestream.Dispose();
                tmpwatrer.Dispose();
                sourceImg.Dispose();
            }
        }
开发者ID:Dason1986,项目名称:Lib,代码行数:32,代码来源:WaterImageBuilderByText.cs

示例15: ConvertToTexture

        public Texture2D ConvertToTexture(Bitmap bitmap)
        {
            Texture2D texture;
            if (bitmap == null)
            {
                return null;
            }

            // MemoryStream to store the bitmap data.
            MemoryStream ms = new MemoryStream();
            // Save image to MemoryStream
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            //Go to the beginning of the memory stream.
            ms.Seek(0, SeekOrigin.Begin);

            //Fill the texture.
            texture = Texture2D.FromStream(graphicsDevice, ms);

            ms.Close();
            ms.Dispose();
            ms = null;

            return texture;
        }
开发者ID:JacquesLucke,项目名称:Collage,代码行数:25,代码来源:ImageLoader.cs


注:本文中的System.IO.MemoryStream.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。