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


C# MemoryStream.TryGetBuffer方法代码示例

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


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

示例1: TryGetBuffer_Constructor_ByteArray_Bool_AlwaysReturnsFalse

    public static void TryGetBuffer_Constructor_ByteArray_Bool_AlwaysReturnsFalse()
    {
        var stream = new MemoryStream(new byte[512], writable: true);

        ArraySegment<byte> segment;
        Assert.False(stream.TryGetBuffer(out segment));
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:MemoryStream_TryGetBufferTests.cs

示例2: TestReader

        private async Task TestReader(string input, string[] expected)
        {
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
            var reader = new ReceiveMessageReader(stream);
            var messages = await reader.ReadMessages();
            Assert.Equal(expected.Length, messages.Count);
            // this is a small buffer to test overflow
            byte[] buffer = new byte[10];
            for (int i = 0; i < expected.Length; i++)
            {
                var decodedStream = new MemoryStream();
                do
                {
                    int length = messages[i].Decode(new ArraySegment<byte>(buffer, 0, buffer.Length));
                    decodedStream.Write(buffer, 0, length);
                } while (!messages[i].IsEmpty);
#if NET451
                ArraySegment<byte> streamBuffer = new ArraySegment<byte>(decodedStream.GetBuffer(), 0, (int)decodedStream.Length);
#else
                ArraySegment<byte> streamBuffer;
                decodedStream.TryGetBuffer(out streamBuffer);
#endif
                var s = Encoding.UTF8.GetString(streamBuffer.Array, streamBuffer.Offset, streamBuffer.Count);
                Assert.Equal(expected[i], s);
            }
        }
开发者ID:tmds,项目名称:Tmds.SockJS,代码行数:26,代码来源:ReaderWriterTest.cs

示例3: TryGetBuffer_Constructor_ByteArray_Int32_Int32_AlwaysReturnsFalse

    public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_AlwaysReturnsFalse()
    {
        var stream = new MemoryStream(new byte[512], index: 0, count: 512);

        ArraySegment<byte> segment;
        Assert.False(stream.TryGetBuffer(out segment));
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:MemoryStream_TryGetBufferTests.cs

示例4: TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_FalseAsPubliclyVisible_ReturnsFalse

    public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_FalseAsPubliclyVisible_ReturnsFalse()
    {
        var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true, publiclyVisible: false);

        ArraySegment<byte> segment;
        Assert.False(stream.TryGetBuffer(out segment));
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:MemoryStream_TryGetBufferTests.cs

示例5: TryGetBuffer_Constructor_AlwaysReturnsTrue

    public static void TryGetBuffer_Constructor_AlwaysReturnsTrue()
    {
        var stream = new MemoryStream();

        ArraySegment<byte> segment;
        Assert.True(stream.TryGetBuffer(out segment));

        Assert.NotNull(segment.Array);
        Assert.Equal(0, segment.Offset);
        Assert.Equal(0, segment.Count);
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:11,代码来源:MemoryStream_TryGetBufferTests.cs

示例6: TryGetBuffer_Constructor_Int32_AlwaysReturnsTrue

    public static void TryGetBuffer_Constructor_Int32_AlwaysReturnsTrue()
    {
        var stream = new MemoryStream(512);

        ArraySegment<byte> segment;
        Assert.True(stream.TryGetBuffer(out segment));

        Assert.Equal(512, segment.Array.Length);
        Assert.Equal(0, segment.Offset);
        Assert.Equal(0, segment.Count);
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:11,代码来源:MemoryStream_TryGetBufferTests.cs

示例7: MemoryStreamToArrayFast

        private static byte[] MemoryStreamToArrayFast(MemoryStream memoryStream)
        {
            // Use the internal buffer when it has the correct length. Otherwise, use .ToArray() which creates a copy of the buffer.

            byte[] buffer = null;
            ArraySegment<byte> bufferSegment;
            if (memoryStream.TryGetBuffer(out bufferSegment))
            {
                buffer = bufferSegment.Array;
            }
            if (buffer == null || buffer.Length != memoryStream.Length)
            {
                buffer = memoryStream.ToArray();
            }
            return buffer;
        }
开发者ID:jbe2277,项目名称:waf,代码行数:16,代码来源:CryptographicService.cs

示例8: ReadMessages

        public async Task<List<JsonString>> ReadMessages()
        {
            var messages = new List<JsonString>();
            using (var memoryStream = new MemoryStream())
            {
                await _body.CopyToAsync(memoryStream);
#if NET451
                var buffer = memoryStream.GetBuffer();
#else
                ArraySegment<byte> segment;
                memoryStream.TryGetBuffer(out segment);
                var buffer = segment.Array;
#endif
                if (buffer.Length == 0)
                {
                    throw new Exception("Payload expected.");
                }
                bool inString = false;
                int startIndex = 0;
                for (int i = 0; i < buffer.Length; i++)
                {
                    byte b = buffer[i];
                    if (!inString && b == (byte)'\"')
                    {
                        inString = true;
                        startIndex = i + 1;
                    }
                    else if (inString && b == (byte)'\\')
                    {
                        i++; // next character is escaped, ignore it
                    }
                    else if (inString && b == (byte)'\"')
                    {
                        inString = false;
                        messages.Add(new JsonString(buffer, startIndex, i));
                    }
                }
                if (inString)
                {
                    throw new Exception("Broken JSON encoding.");
                }
            }
            return messages;
        }
开发者ID:tmds,项目名称:Tmds.SockJS,代码行数:44,代码来源:ReceiveMessageReader.cs

示例9: AudioFileStream

        /// <summary>
        ///     Creates a sample stream from an MP3, MP2, MP1, OGG, WAV, AIFF or plug-in supported memory stream.
        /// </summary>
        /// <param name="stream">Memory stream.</param>
        /// <param name="configs">Configure of <see cref="AudioFileStream" />.</param>
        public AudioFileStream(MemoryStream stream, StreamCreateFileConfig configs)
        {
            ArraySegment<byte> bufferSegment;
            byte[] buffer = null;
            if (stream.TryGetBuffer(out bufferSegment))
            {
                buffer = bufferSegment.Array;
            }
            else
            {
                buffer = stream.ToArray();
            }

            GCHandle bufferHandle = GCHandle.Alloc(buffer);

            Handle = AudioStreamModule.StreamCreateFileFunction.CheckResult(
                AudioStreamModule.StreamCreateFileFunction.Delegate(true,
                    bufferHandle.AddrOfPinnedObject(), 0, (uint) stream.Length, configs));

            bufferHandle.Free();
        }
开发者ID:higankanshi,项目名称:xZune.Bass,代码行数:26,代码来源:AudioFileStream.cs

示例10: TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_TrueAsPubliclyVisible_ReturnsTrue

    public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_TrueAsPubliclyVisible_ReturnsTrue()
    {
        var stream = new MemoryStream(new byte[512], index: 0, count: 512, writable: true, publiclyVisible: true);

        ArraySegment<byte> segment;
        Assert.True(stream.TryGetBuffer(out segment));

        Assert.NotNull(segment.Array);
        Assert.Equal(512, segment.Array.Length);
        Assert.Equal(0, segment.Offset);
        Assert.Equal(512, segment.Count);
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:12,代码来源:MemoryStream_TryGetBufferTests.cs

示例11: WriteMessage

        public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
        {
            ArraySegment<byte> messageBuffer;
            int messageLength;
            using (MemoryStream stream = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(stream, _writerSettings))
                {
                    message.WriteMessage(writer);
                }

                stream.TryGetBuffer(out messageBuffer);
                messageLength = (int)stream.Position;
            }

            int totalLength = messageLength + messageOffset;
            byte[] totalBytes = bufferManager.TakeBuffer(totalLength);
            Array.Copy(messageBuffer.Array, 0, totalBytes, messageOffset, messageLength);

            ArraySegment<byte> byteArray = new ArraySegment<byte>(totalBytes, messageOffset, messageLength);
            return byteArray;
        }
开发者ID:weshaggard,项目名称:wcf,代码行数:22,代码来源:CustomTextMessageEncoder.cs

示例12: MemoryStream

    public static void TryGetBuffer_Constructor_ByteArray_Int32_Int32_Bool_Bool_ValueAsBufferAndTrueAsPubliclyVisible_AlwaysReturnsArraySetToBuffer(ArraySegment<byte> array)
    {
        var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true);

        ArraySegment<byte> result;
        Assert.True(stream.TryGetBuffer(out result));

        Assert.Same(array.Array, result.Array);
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:9,代码来源:MemoryStream_TryGetBufferTests.cs

示例13: TryGetBuffer_WhenDisposed_ReturnsArraySetToBuffer

    public static void TryGetBuffer_WhenDisposed_ReturnsArraySetToBuffer(ArraySegment<byte> array)
    {
        var stream = new MemoryStream(array.Array, index: array.Offset, count: array.Count, writable: true, publiclyVisible: true);
        stream.Dispose();

        ArraySegment<byte> result;
        Assert.True(stream.TryGetBuffer(out result));

        Assert.Same(array.Array, result.Array);
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:10,代码来源:MemoryStream_TryGetBufferTests.cs

示例14: ExtractFilesFromArchive

        private async Task ExtractFilesFromArchive(Stream strm)
        {
            var arch = ArchiveFactory.Open(strm);
            foreach (var entry in arch.Entries)
            {
                if (!entry.IsDirectory)
                {
                    using (var ms = new MemoryStream())
                    {
                        try
                        {
                            entry.WriteTo(ms);
                        }
                        catch (Exception ex) { }
                        ms.Seek(0, SeekOrigin.Begin);
                        var buffer = new ArraySegment<byte>();
                        ms.TryGetBuffer(out buffer);

                        Files.Add(new FileEntry(entry.Key, buffer.Array));
                    }
                }
            }
            
        }
开发者ID:DevTheo,项目名称:IFControlDemo,代码行数:24,代码来源:ArchiveAndLocalBasedFileService.cs

示例15: CustomTextMessageEncoder_Http_RequestReply_Streamed

    public static void CustomTextMessageEncoder_Http_RequestReply_Streamed()
    {
        // 84K, larger than any buffers, but won't allocate in LOH
        int streamKBytes = 84;
        int streamLength = 1024 * streamKBytes;
        int lowestPrintable = ' ';
        int printableRange = '~' - lowestPrintable;
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        Stream stream = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(new CustomTextMessageBindingElement(Encoding.UTF8.WebName),
                new HttpTransportBindingElement
                {
                    MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB,
                    MaxBufferSize = ScenarioTestHelpers.SixtyFourMB,
                    TransferMode = TransferMode.Streamed
                });

            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.CustomTextEncoderStreamed_Address));
            serviceProxy = factory.CreateChannel();
            byte[] requestBytes = new byte[streamLength];
            RandomNumberGenerator rnd = RandomNumberGenerator.Create();
            int pos = 0;
            for (int i = 0; i < streamKBytes; i++)
            {
                byte[] tempBuffer = new byte[1024];
                rnd.GetBytes(tempBuffer);
                for (int j = 0; j < 1024; j++)
                {
                    byte val = tempBuffer[j];
                    if (val < ' ' || val > '~')
                    {
                        // Force the value to be between ' ' and '~'
                        int temp1 = val % printableRange;
                        val = (byte)(temp1 + lowestPrintable);
                    }

                    requestBytes[pos++] = val;
                }
            }
            stream = new MemoryStream(requestBytes);

            // *** EXECUTE *** \\
            var returnStream = serviceProxy.EchoStream(stream);

            // *** VALIDATE *** \\
            MemoryStream ms = new MemoryStream(streamLength);
            returnStream.CopyTo(ms);

            Assert.True(streamLength == ms.Length,
                        String.Format("Expected returned stream length = {0}, actual = {1}",
                                        streamLength, ms.Length));

            ArraySegment<byte> returnedByteArraySegment;
            ms.TryGetBuffer(out returnedByteArraySegment);
            Assert.True(requestBytes.SequenceEqual(returnedByteArraySegment.Array), "Returned bytes are different than sent bytes");

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
开发者ID:weshaggard,项目名称:wcf,代码行数:71,代码来源:TextTests.cs


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