MemoryStream 类

定义

创建一个支持存储为内存的流。

public ref class MemoryStream : System::IO::Stream
public class MemoryStream : System.IO.Stream
[System.Serializable]
public class MemoryStream : System.IO.Stream
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class MemoryStream : System.IO.Stream
type MemoryStream = class
    inherit Stream
[<System.Serializable>]
type MemoryStream = class
    inherit Stream
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MemoryStream = class
    inherit Stream
Public Class MemoryStream
Inherits Stream
继承
MemoryStream
继承
属性

示例

下面的代码示例演示如何使用内存作为后盾存储来读取和写入数据。

using System;
using System.IO;
using System.Text;

class MemStream
{
    static void Main()
    {
        int count;
        byte[] byteArray;
        char[] charArray;
        UnicodeEncoding uniEncoding = new UnicodeEncoding();

        // Create the data to write to the stream.
        byte[] firstString = uniEncoding.GetBytes(
            "Invalid file path characters are: ");
        byte[] secondString = uniEncoding.GetBytes(
            Path.GetInvalidPathChars());

        using(MemoryStream memStream = new MemoryStream(100))
        {
            // Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length);

            // Write the second string to the stream, byte by byte.
            count = 0;
            while(count < secondString.Length)
            {
                memStream.WriteByte(secondString[count++]);
            }

            // Write the stream properties to the console.
            Console.WriteLine(
                "Capacity = {0}, Length = {1}, Position = {2}\n",
                memStream.Capacity.ToString(),
                memStream.Length.ToString(),
                memStream.Position.ToString());

            // Set the position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin);

            // Read the first 20 bytes from the stream.
            byteArray = new byte[memStream.Length];
            count = memStream.Read(byteArray, 0, 20);

            // Read the remaining bytes, byte by byte.
            while(count < memStream.Length)
            {
                byteArray[count++] = (byte)memStream.ReadByte();
            }

            // Decode the byte array into a char array
            // and write it to the console.
            charArray = new char[uniEncoding.GetCharCount(
                byteArray, 0, count)];
            uniEncoding.GetDecoder().GetChars(
                byteArray, 0, count, charArray, 0);
            Console.WriteLine(charArray);
        }
    }
}
Imports System.IO
Imports System.Text

Module MemStream

    Sub Main()
    
        Dim count As Integer
        Dim byteArray As Byte()
        Dim charArray As Char()
        Dim uniEncoding As New UnicodeEncoding()

        ' Create the data to write to the stream.
        Dim firstString As Byte() = _
            uniEncoding.GetBytes("Invalid file path characters are: ")
        Dim secondString As Byte() = _
            uniEncoding.GetBytes(Path.GetInvalidPathChars())

        Dim memStream As New MemoryStream(100)
        Try
            ' Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length)

            ' Write the second string to the stream, byte by byte.
            count = 0
            While(count < secondString.Length)
                memStream.WriteByte(secondString(count))
                count += 1
            End While
            
            ' Write the stream properties to the console.
            Console.WriteLine( _
                "Capacity = {0}, Length = {1}, Position = {2}", _
                memStream.Capacity.ToString(), _
                memStream.Length.ToString(), _
                memStream.Position.ToString())

            ' Set the stream position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin)

            ' Read the first 20 bytes from the stream.
            byteArray = _
                New Byte(CType(memStream.Length, Integer)){}
            count = memStream.Read(byteArray, 0, 20)

            ' Read the remaining Bytes, Byte by Byte.
            While(count < memStream.Length)
                byteArray(count) = _
                    Convert.ToByte(memStream.ReadByte())
                count += 1
            End While

            ' Decode the Byte array into a Char array 
            ' and write it to the console.
            charArray = _
                New Char(uniEncoding.GetCharCount( _
                byteArray, 0, count)){}
            uniEncoding.GetDecoder().GetChars( _
                byteArray, 0, count, charArray, 0)
            Console.WriteLine(charArray)
        Finally
            memStream.Close()
        End Try

    End Sub
End Module

注解

流的当前位置是下一次读取或写入操作的发生位置。 可以通过方法检索或设置 Seek 当前位置。 创建新实例 MemoryStream 时,当前位置设置为零。

注释

此类型实现 IDisposable 接口,但实际上没有任何要释放的资源。 这意味着,无需直接调用 Dispose() 或使用 using(在 C# 中)或 Using(Visual Basic)等语言构造来释放它。

使用无符号字节数组创建的内存流提供不可调整大小的数据流。 使用字节数组时,既不能追加流,也不能收缩流,尽管根据传递给构造函数的参数,可以修改现有内容。 空内存流可以调整大小,并且可以写入和读取。

MemoryStream如果将对象添加到 ResX 文件或 .resources 文件,请在运行时调用GetStream该方法以检索它。

MemoryStream如果将对象序列化为资源文件,它实际上将序列化为一个 UnmanagedMemoryStream。 此行为可提供更好的性能,并能够直接获取指向数据的指针,而无需通过 Stream 方法。

构造函数

名称 说明
MemoryStream()

使用可扩展容量初始化为零的类的新实例 MemoryStream

MemoryStream(Byte[], Boolean)

根据指定的字节数组,使用CanWrite指定的属性集初始化类的新不可调整大小的实例MemoryStream

MemoryStream(Byte[], Int32, Int32, Boolean, Boolean)

根据字节数组的指定区域初始化类的新实例 MemoryStream ,并 CanWrite 指定属性集,并能够按指定方式调用 GetBuffer() 集。

MemoryStream(Byte[], Int32, Int32, Boolean)

根据字节数组的指定区域初始化类的新不可调整大小的实例 MemoryStream ,并将 CanWrite 属性设置为指定。

MemoryStream(Byte[], Int32, Int32)

根据字节数组的指定区域(索引)初始化类的新不可调整大小的实例 MemoryStream

MemoryStream(Byte[])

基于指定的字节数组初始化类的新不可调整大小的实例 MemoryStream

MemoryStream(Int32)

使用已指定初始化的可扩展容量初始化类的新实例 MemoryStream

属性

名称 说明
CanRead

获取一个值,该值指示当前流是否支持读取。

CanSeek

获取一个值,该值指示当前流是否支持查找。

CanTimeout

获取一个值,该值确定当前流是否可以超时。

(继承自 Stream)
CanWrite

获取一个值,该值指示当前流是否支持写入。

Capacity

获取或设置为此流分配的字节数。

Length

获取流的长度(以字节为单位)。

Position

获取或设置流中的当前位置。

ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取的时间。

(继承自 Stream)
WriteTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时之前尝试写入的时间。

(继承自 Stream)

方法

名称 说明
BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步读取操作。 (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步读取操作。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)

(继承自 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)

(继承自 Stream)
Close()

关闭用于读取和写入的流。

Close()

关闭当前流并释放与当前流关联的任何资源(如套接字和文件句柄)。 请确保流已正确释放,而不是调用此方法。

(继承自 Stream)
CopyTo(Stream, Int32)

使用指定的缓冲区大小从当前内存流中读取字节并将其写入另一个流。

CopyTo(Stream, Int32)

从当前流中读取字节,并使用指定的缓冲区大小将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyTo(Stream)

从当前流中读取字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消标记异步读取当前流中的字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消标记以异步方式读取当前流中的所有字节,并将其写入另一个流。

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消令牌异步读取当前流中的字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream, Int32)

使用指定的缓冲区大小异步读取当前流中的字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream)

从当前流异步读取字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CreateObjRef(Type)

创建一个对象,其中包含生成用于与远程对象通信的代理所需的所有相关信息。

(继承自 MarshalByRefObject)
CreateWaitHandle()
已过时.

分配对象 WaitHandle

(继承自 Stream)
Dispose()

释放该 Stream命令使用的所有资源。

(继承自 Stream)
Dispose(Boolean)

释放类使用 MemoryStream 的非托管资源,并选择性地释放托管资源。

DisposeAsync()

异步释放由 <a0/a0> 使用的非托管资源。

(继承自 Stream)
EndRead(IAsyncResult)

等待挂起的异步读取完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)

EndRead(IAsyncResult)

等待挂起的异步读取完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)

(继承自 Stream)
EndWrite(IAsyncResult)

结束异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)

EndWrite(IAsyncResult)

结束异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)

(继承自 Stream)
Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
Flush()

Flush()重写该方法,以便不执行任何操作。

FlushAsync()

异步清除此流的所有缓冲区,并导致任何缓冲数据写入基础设备。

(继承自 Stream)
FlushAsync(CancellationToken)

异步清除此流的所有缓冲区,并监视取消请求。

GetBuffer()

返回从中创建此流的无符号字节数组。

GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
ObjectInvariant()

此 API 支持产品基础结构,不能在代码中直接使用。

提供对 a Contract.

ObjectInvariant()
已过时.

提供对 a Contract.

(继承自 Stream)
Read(Byte[], Int32, Int32)

从当前流中读取字节块并将数据写入缓冲区。

Read(Span<Byte>)

从当前内存流中读取字节序列,并通过读取的字节数推进内存流中的位置。

ReadAsync(Byte[], Int32, Int32, CancellationToken)

从当前流异步读取字节序列,按读取的字节数推进流中的位置,并监视取消请求。

ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并通过读取的字节数推进流中的位置。

(继承自 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

从当前内存流异步读取字节序列,将序列 destination写入其中,按读取的字节数推进内存流中的位置,并监视取消请求。

ReadByte()

从当前流读取字节。

Seek(Int64, SeekOrigin)

将当前流中的位置设置为指定值。

SetLength(Int64)

将当前流的长度设置为指定值。

ToArray()

无论 Position 属性如何,将流内容写入字节数组。

ToString()

返回一个表示当前对象的字符串。

(继承自 Object)
TryGetBuffer(ArraySegment<Byte>)

返回从中创建此流的无符号字节数组。 返回值指示转换是否成功。

Write(Byte[], Int32, Int32)

使用从缓冲区读取的数据将字节块写入当前流。

Write(ReadOnlySpan<Byte>)

将包含在当前内存流中的 source 字节序列写入到当前内存流中,并按写入的字节数推进此内存流中的当前位置。

WriteAsync(Byte[], Int32, Int32, CancellationToken)

将字节序列异步写入当前流,按写入的字节数推进此流中的当前位置,并监视取消请求。

WriteAsync(Byte[], Int32, Int32)

以异步方式将字节序列写入当前流,并通过写入的字节数推进此流中的当前位置。

(继承自 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以异步方式将包含在 source 当前内存流的字节序列中,按写入的字节数推进此内存流中的当前位置,并监视取消请求。

WriteByte(Byte)

将字节写入当前位置的当前流。

WriteTo(Stream)

将此内存流的整个内容写入另一个流。

显式接口实现

名称 说明
IDisposable.Dispose()

释放该 Stream命令使用的所有资源。

(继承自 Stream)

扩展方法

名称 说明
AsInputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输入流。

AsOutputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输出流。

AsRandomAccessStream(Stream)

将指定的流转换为随机访问流。

ConfigureAwait(IAsyncDisposable, Boolean)

配置如何执行从异步可释放项返回的任务的 await。

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

返回Windows。Storage.Streams.IBuffer 接口,该接口表示指定内存流所表示的内存中的区域。

GetWindowsRuntimeBuffer(MemoryStream)

返回Windows。Storage.Streams.IBuffer 接口,该接口表示与指定的内存流相同的内存。

适用于

另请参阅