MemoryStream 类 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
创建一个支持存储为内存的流。
public ref class MemoryStream : System::IO::Streampublic 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.Streamtype MemoryStream = class
    inherit Stream[<System.Serializable>]
type MemoryStream = class
    inherit Stream[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MemoryStream = class
    inherit StreamPublic Class MemoryStream
Inherits Stream- 继承
- 继承
- 属性
示例
下面的代码示例演示如何使用内存作为后盾存储来读取和写入数据。
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() 或使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造来释放它。
使用无符号字节数组创建的内存流提供不可调整大小的数据流。 使用字节数组时,既不能追加流,也不能收缩流,尽管根据传递给构造函数的参数,可以修改现有内容。 空内存流可以调整大小,并且可以写入和读取。
如果将 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) | 
方法
显式接口实现
| IDisposable.Dispose() | 释放 Stream使用的所有资源。(继承自 Stream) | 
扩展方法
| CopyToAsync(Stream, PipeWriter, CancellationToken) | 使用取消令牌从 Stream 异步读取字节并将其写入指定的 PipeWriter。 | 
| 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) | 配置如何执行从异步可释放项返回的任务的 await。 |