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 namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   int count;
   array<Byte>^byteArray;
   array<Char>^charArray;
   UnicodeEncoding^ uniEncoding = gcnew UnicodeEncoding;

   // Create the data to write to the stream.
   array<Byte>^firstString = uniEncoding->GetBytes( "Invalid file path characters are: " );
   array<Byte>^secondString = uniEncoding->GetBytes( Path::InvalidPathChars );

   MemoryStream^ memStream = gcnew 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++ ] );
      }

      
      // 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 stream position to the beginning of the stream.
      memStream->Seek( 0, SeekOrigin::Begin );

      // Read the first 20 bytes from the stream.
      byteArray = gcnew array<Byte>(memStream->Length);
      count = memStream->Read( byteArray, 0, 20 );

      // Read the remaining bytes, byte by byte.
      while ( count < memStream->Length )
      {
         byteArray[ count++ ] = Convert::ToByte( memStream->ReadByte() );
      }
      
      // Decode the Byte array into a Char array 
      // and write it to the console.
      charArray = gcnew array<Char>(uniEncoding->GetCharCount( byteArray, 0, count ));
      uniEncoding->GetDecoder()->GetChars( byteArray, 0, count, charArray, 0 );
      Console::WriteLine( charArray );
   }
   finally
   {
      memStream->Close();
   }
}
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() 或使用语言构造(C# 中的 using 或 Visual Basic 中的 Using)对其进行处理。

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

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

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

构造函数

MemoryStream()

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

MemoryStream(Byte[])

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

MemoryStream(Byte[], Boolean)

CanWrite 属性按指定设置的状态下,基于指定的字节数组初始化 MemoryStream 类的无法调整大小的新实例。

MemoryStream(Byte[], Int32, Int32)

基于字节数组的指定区域(索引)初始化 MemoryStream 类的无法调整大小的新实例。

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

MemoryStream 属性按指定设置的状态下,基于字节数组的指定区域,初始化 CanWrite 类的无法调整大小的新实例。

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

MemoryStream 属性和调用 CanWrite 的能力按指定设置的状态下,基于字节数组的指定区域初始化 GetBuffer() 类的新实例。

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)

从当前流中读取字节并将其写入到另一流中。

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

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

CopyTo(Stream, Int32)

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

(继承自 Stream)
CopyToAsync(Stream)

从当前流中异步读取字节并将其写入到另一个流中。

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

通过指定的取消令牌,从当前流中异步读取字节并将其写入到另一个流中。

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

使用指定的缓冲区大小,从当前流中异步读取字节并将其写入到另一流中。

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

使用指定的缓冲区大小和取消令牌,从当前流中异步读取所有字节并将其写入到另一个流中。

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消令牌,从当前流中异步读取字节并将其写入到另一个流中。

(继承自 Stream)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

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

分配 WaitHandle 对象。

(继承自 Stream)
Dispose()

释放由 Stream 使用的所有资源。

(继承自 Stream)
Dispose(Boolean)

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

Dispose(Boolean)

释放由 Stream 占用的非托管资源,还可以另外再释放托管资源。

(继承自 Stream)
DisposeAsync()

异步释放 Stream 使用的非托管资源。

(继承自 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)

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

FlushAsync(CancellationToken)

异步清理此流的所有缓冲区,导致所有缓冲数据都写入基础设备,并且监控取消请求。

(继承自 Stream)
GetBuffer()

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

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时。

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

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时。

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

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

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

(继承自 MarshalByRefObject)
ObjectInvariant()

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

提供对 Contract 的支持。

ObjectInvariant()
已过时。

提供对 Contract 的支持。

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

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

Read(Span<Byte>)

从当前内存流读取字节序列,并将内存流中的位置向前移动读取的字节数。

Read(Span<Byte>)

当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数。

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

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

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

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

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

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

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

ReadAsync(Memory<Byte>, CancellationToken)

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

(继承自 Stream)
ReadByte()

从当前流中读取一个字节。

Seek(Int64, SeekOrigin)

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

SetLength(Int64)

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

ToArray()

将流内容写入字节数组,而与 Position 属性无关。

ToString()

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

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

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

Write(Byte[], Int32, Int32)

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

Write(ReadOnlySpan<Byte>)

source 中包含的字节序列写入当前内存流,并按写入的字节数向前移动内存流的当前位置。

Write(ReadOnlySpan<Byte>)

当在派生类中重写时,向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数。

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

将字节序列异步写入当前流,并将流的当前位置提升写入的字节数。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

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

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

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

source 中包含的字节序列异步写入当前内存流,按写入的字节数向前移动该内存流中的当前位置,并监视取消请求。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

(继承自 Stream)
WriteByte(Byte)

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

WriteTo(Stream)

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

显式接口实现

IDisposable.Dispose()

释放由 Stream 使用的所有资源。

(继承自 Stream)

扩展方法

AsInputStream(Stream)

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

AsOutputStream(Stream)

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

AsRandomAccessStream(Stream)

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

GetWindowsRuntimeBuffer(MemoryStream)

返回一个 Windows.Storage.Streams.IBuffer 接口,该接口将同一内存表示为指定内存流。

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

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

ConfigureAwait(IAsyncDisposable, Boolean)

配置如何执行从异步可处置项返回的任务的等待。

适用于

另请参阅