.NET Framework 类库
MemoryStream 类
创建其支持存储区为内存的流。
命名空间: System.IO
程序集: mscorlib(在 mscorlib.dll 中)
语法
Visual Basic(声明)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class MemoryStream _
Inherits Stream
Visual Basic(用法)
Dim instance As MemoryStream
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class MemoryStream : Stream
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class MemoryStream : public Stream
J#
/** @attribute SerializableAttribute */
/** @attribute ComVisibleAttribute(true) */
public class MemoryStream extends Stream
JScript
public class MemoryStream extends Stream
备注
有关创建文件和向文件中写入文本的示例,请参见 如何:向文件写入文本。有关从文件中读取文本的示例,请参见 如何:从文件读取文本。有关读取和写入二进制文件的示例,请参见 如何:对新建的数据文件进行读取和写入。
MemoryStream 类创建这样的流,该流以内存而不是磁盘或网络连接作为支持存储区。MemoryStream 封装以无符号字节数组形式存储的数据,该数组在创建 MemoryStream 对象时被初始化,或者该数组可创建为空数组。可在内存中直接访问这些封装的数据。内存流可降低应用程序中对临时缓冲区和临时文件的需要。
流的当前位置是下一个读取或写入操作可能发生的位置。当前位置可以通过 Seek 方法检索或设置。在创建 MemoryStream 的新实例时,当前位置设置为零。
用无符号字节数组创建的内存流提供无法调整大小的数据流视图,而且只能向其写入。当使用字节数组时,虽然根据传递到构造函数中的参数可能能够修改现有内容,但既不能追加也不能收缩流。空内存流是可调整大小的,而且可以向其写入和从中读取。
如果将 MemoryStream 对象添加到 ResX 文件或 .resources 文件中,则可在运行时调用 GetStream 方法对其进行检索。
如果将 MemoryStream 对象序列化为资源文件,它将被实际序列化为 UnmanagedMemoryStream。此行为可以提供更好的性能,并可以提供将指针直接指向数据的功能,而不必使用 Stream 方法。
Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE 平台说明:
在 Windows CE 中,从剪贴板粘贴的内存流的大小可以比复制到剪贴板的内存流稍微大一点,因为可以在原始内存流的结尾附加额外的字节。若要准确检索内存流,请将对象的大小作为该对象的前缀来确定其接收方式,或将 DataObject 复制到剪贴板,其中包含该内存流和表示其大小的字符串值。
示例
下面的代码示例说明如何通过将内存用作备份来读取和写入数据。
Visual Basic 复制代码
Imports System
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.InvalidPathChars)
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
C# 复制代码
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.InvalidPathChars);
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}
",
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);
}
}
}
Visual C++ 复制代码
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}
", 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();
}
}
J# 复制代码
import System.*;
import System.IO.*;
import System.Text.*;
class MemStream
{
public static void main(String[] args)
{
int count;
ubyte byteArray[];
char charArray[];
UnicodeEncoding uniEncoding = new UnicodeEncoding();
// Create the data to write to the stream.
ubyte firstString[] = uniEncoding.GetBytes(
"Invalid file path characters are: ");
ubyte secondString[] = uniEncoding.GetBytes(Path.InvalidPathChars);
MemoryStream memStream = 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++]);
}
// Write the stream properties to the console.
Console.WriteLine(
"Capacity = {0}, Length = {1}, Position = {2}
",
(new Integer( memStream.get_Capacity())).ToString(),
(new Long ( memStream.get_Length())).ToString(),
(new Long ( memStream.get_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 ubyte[(int)memStream.get_Length()];
count = memStream.Read(byteArray, 0, 20);
// Read the remaining bytes, byte by byte.
while ((count < memStream.get_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);
}
finally {
memStream.Dispose();
}
}//main
} //MemStream
继承层次结构
System..::.Object
System..::.MarshalByRefObject
System.IO..::.Stream
System.IO..::.MemoryStream
线程安全
此类型的任何公共 static(在 Visual Basic中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。
平台
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360
.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。
版本信息
.NET Framework
受以下版本支持:3.5、3.0 SP1、3.0、2.0 SP1、2.0、1.1、1.0
.NET Compact Framework
受以下版本支持:3.5、2.0、1.0
XNA Framework
受以下版本支持:1.0