MemoryStream 类

定义

创建一个流,其后备存储为内存。Creates a stream whose backing store is memory.

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

示例

下面的代码示例演示如何使用内存作为后备存储来读取和写入数据。The following code example shows how to read and write data using memory as a backing store.

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++] =
                    Convert.ToByte(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

注解

流的当前位置是指下一次读取或写入操作可能发生的位置。The current position of a stream is the position at which the next read or write operation could take place. 可以通过 Seek 方法检索或设置当前位置。The current position can be retrieved or set through the Seek method. 创建 MemoryStream 的新实例时,当前位置设置为零。When a new instance of MemoryStream is created, the current position is set to zero.

备注

此类型可实现 IDisposable 接口,但实际上没有任何要释放的资源。This type implements the IDisposable interface, but does not actually have any resources to dispose. 这意味着无需通过直接调用 Dispose() 或使用语言构造(C# 中的 using 或 Visual Basic 中的 Using)对其进行处理。This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.

使用无符号字节数组创建的内存流提供了不可调整大小的数据流。Memory streams created with an unsigned byte array provide a non-resizable stream of the data. 使用字节数组时,既不能追加到流,也不能收缩流,尽管可以根据传入构造函数的参数来修改现有内容。When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor. 空内存流可调整大小,并可进行写入和读取。Empty memory streams are resizable, and can be written to and read from.

如果 MemoryStream 对象添加到 ResX 文件或 .resources 文件,请在运行时调用 GetStream 方法以检索它。If a MemoryStream object is added to a ResX file or a .resources file, call the GetStream method at runtime to retrieve it.

如果 MemoryStream 对象序列化为资源文件,则该对象实际上会序列化为 UnmanagedMemoryStreamIf a MemoryStream object is serialized to a resource file it will actually be serialized as an UnmanagedMemoryStream. 此行为可提供更好的性能,并且能够直接获取指向数据的指针,而无需经过 Stream 方法。This behavior provides better performance, as well as the ability to get a pointer to the data directly, without having to go through Stream methods.

构造函数

MemoryStream()

使用初始化为零的可扩展容量初始化 MemoryStream 类的新实例。Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero.

MemoryStream(Byte[])

基于指定的字节数组初始化 MemoryStream 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array.

MemoryStream(Byte[], Boolean)

CanWrite 属性按指定设置的状态下,基于指定的字节数组初始化 MemoryStream 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array with the CanWrite property set as specified.

MemoryStream(Byte[], Int32, Int32)

基于字节数组的指定区域(索引)初始化 MemoryStream 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified region (index) of a byte array.

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

MemoryStream 属性按指定设置的状态下,基于字节数组的指定区域,初始化 CanWrite 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified.

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

MemoryStream 属性和调用 CanWrite 的能力按指定设置的状态下,基于字节数组的指定区域初始化 GetBuffer() 类的新实例。Initializes a new instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified, and the ability to call GetBuffer() set as specified.

MemoryStream(Int32)

使用按指定要求初始化的可扩展容量初始化 MemoryStream 类的新实例。Initializes a new instance of the MemoryStream class with an expandable capacity initialized as specified.

属性

CanRead

获取一个值,该值指示当前流是否支持读取。Gets a value indicating whether the current stream supports reading.

CanSeek

获取一个值,该值指示当前流是否支持查找。Gets a value indicating whether the current stream supports seeking.

CanTimeout

获取一个值,该值确定当前流是否可以超时。Gets a value that determines whether the current stream can time out.

(继承自 Stream)
CanWrite

获取一个值,该值指示当前流是否支持写入。Gets a value indicating whether the current stream supports writing.

Capacity

获取或设置分配给该流的字节数。Gets or sets the number of bytes allocated for this stream.

Length

获取流的长度(以字节为单位)。Gets the length of the stream in bytes.

Position

获取或设置流中的当前位置。Gets or sets the current position within the stream.

ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取多长时间。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(继承自 Stream)
WriteTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试写入多长时间。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(继承自 Stream)

方法

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

开始异步读操作。Begins an asynchronous read operation. (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)。)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

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

开始异步写操作。Begins an asynchronous write operation. (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)。)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Close()

关闭读写流。Closes the stream for reading and writing.

CopyTo(Stream)

从当前流中读取字节并将其写入到另一流中。Reads the bytes from the current stream and writes them to another stream.

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

使用指定的缓冲区大小,从当前内存流中读取字节并将其写入到另一流中。Reads the bytes from the current memory stream and writes them to another stream, using a specified buffer size.

CopyToAsync(Stream)

从当前流中异步读取字节并将其写入到另一个流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

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

通过指定的取消令牌,从当前流中异步读取字节并将其写入到另一个流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

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

使用指定的缓冲区大小,从当前流中异步读取字节并将其写入到另一流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

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

从当前流中异步读取所有字节并将其写入到另一个流中(使用指定的缓冲区大小和取消令牌)。Asynchronously reads all the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
CreateWaitHandle()

分配 WaitHandle 对象。Allocates a WaitHandle object.

(继承自 Stream)
Dispose()

释放由 Stream 使用的所有资源。Releases all resources used by the Stream.

(继承自 Stream)
Dispose(Boolean)

释放 MemoryStream 类使用的非托管资源,并可以选择释放托管资源。Releases the unmanaged resources used by the MemoryStream class and optionally releases the managed resources.

DisposeAsync()

异步释放 Stream 使用的非托管资源。Asynchronously releases the unmanaged resources used by the Stream.

(继承自 Stream)
EndRead(IAsyncResult)

等待挂起的异步读取完成。Waits for the pending asynchronous read to complete. (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)。)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

EndWrite(IAsyncResult)

结束异步写操作。Ends an asynchronous write operation. (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)。)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Flush()

重写 Flush() 方法以便不执行任何操作。Overrides the Flush() method so that no action is performed.

FlushAsync()

异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(继承自 Stream)
FlushAsync(CancellationToken)

异步清除此流的所有缓冲区,并监视取消请求。Asynchronously clears all buffers for this stream, and monitors cancellation requests.

GetBuffer()

返回从中创建此流的无符号字节的数组。Returns the array of unsigned bytes from which this stream was created.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
ObjectInvariant()

提供对 Contract 的支持。Provides support for a Contract.

Read(Byte[], Int32, Int32)

从当前流中读取字节块并将数据写入缓冲区中。Reads a block of bytes from the current stream and writes the data to a buffer.

Read(Span<Byte>)

从当前内存流读取字节序列,并将内存流中的位置向前移动读取的字节数。Reads a sequence of bytes from the current memory stream and advances the position within the memory stream by the number of bytes read.

ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

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

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

从当前内存流异步读取字节的序列,将该序列写入 destination,按读取的字节数向前移动内存流中的位置,并监视取消请求。Asynchronously reads a sequence of bytes from the current memory stream, writes the sequence into destination, advances the position within the memory stream by the number of bytes read, and monitors cancellation requests.

ReadByte()

从当前流中读取一个字节。Reads a byte from the current stream.

Seek(Int64, SeekOrigin)

将当前流中的位置设置为指定值。Sets the position within the current stream to the specified value.

SetLength(Int64)

将当前流的长度设为指定值。Sets the length of the current stream to the specified value.

ToArray()

将流内容写入字节数组,而与 Position 属性无关。Writes the stream contents to a byte array, regardless of the Position property.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

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

返回从其创建此流的无符号字节数组。Returns the array of unsigned bytes from which this stream was created. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

Write(Byte[], Int32, Int32)

使用从缓冲区读取的数据将字节块写入当前流。Writes a block of bytes to the current stream using data read from a buffer.

Write(ReadOnlySpan<Byte>)

source 中包含的字节序列写入当前内存流,并按写入的字节数向前移动内存流的当前位置。Writes the sequence of bytes contained in source into the current memory stream and advances the current position within this memory stream by the number of bytes written.

WriteAsync(Byte[], Int32, Int32)

将字节序列异步写入当前流,并将流的当前位置提升写入的字节数。Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

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

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

source 中包含的字节序列异步写入当前内存流,按写入的字节数向前移动该内存流中的当前位置,并监视取消请求。Asynchronously writes the sequence of bytes contained in source into the current memory stream, advances the current position within this memory stream by the number of bytes written, and monitors cancellation requests.

WriteByte(Byte)

将一个字节写入当前流中的当前位置。Writes a byte to the current stream at the current position.

WriteTo(Stream)

将此内存流的整个内容写入到另一个流中。Writes the entire contents of this memory stream to another stream.

显式界面实现

IDisposable.Dispose()

释放由 Stream 使用的所有资源。Releases all resources used by the Stream.

(继承自 Stream)

扩展方法

AsInputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输入流。Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输出流。Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream(Stream)

将指定的流转换为随机访问流。Converts the specified stream to a random access stream.

GetWindowsRuntimeBuffer(MemoryStream)

返回一个 Windows.Storage.Streams.IBuffer 接口,该接口将同一内存表示为指定内存流。Returns a Windows.Storage.Streams.IBuffer interface that represents the same memory as the specified memory stream.

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

返回一个 Windows.Storage.Streams.IBuffer 接口,该接口表示由指定内存流所表示的内存中的一个区域。Returns a Windows.Storage.Streams.IBuffer interface that represents a region within the memory that the specified memory stream represents.

适用于

另请参阅