다음을 통해 공유


MemoryStream 클래스

백업 저장소가 메모리인 스트림을 만듭니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class MemoryStream
    Inherits Stream
‘사용 방법
Dim instance As MemoryStream
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class MemoryStream : Stream
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class MemoryStream : public Stream
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class MemoryStream extends Stream
SerializableAttribute 
ComVisibleAttribute(true) 
public class MemoryStream extends Stream

설명

파일을 만들고 파일에 텍스트를 쓰는 방법에 대한 예제를 보려면 방법: 파일에 텍스트 쓰기를 참조하십시오. 파일에서 텍스트를 읽는 방법에 대한 예제를 보려면 방법: 파일의 텍스트 읽기를 참조하십시오. 이진 파일을 읽거나 쓰는 방법에 대한 예제를 보려면 방법: 새로 만든 데이터 파일 읽기 및 쓰기를 참조하십시오.

MemoryStream 클래스에서는 디스크나 네트워크 연결 대신 메모리를 백업 저장소로 사용하는 스트림을 만듭니다. MemoryStream에서는 MemoryStream 개체 작성 시 초기화되거나 비어 있게 만들어진 부호 없는 바이트 배열로 저장된 데이터를 캡슐화합니다. 캡슐화된 데이터는 메모리에서 직접 액세스할 수 있습니다. 메모리 스트림을 사용하면 응용 프로그램의 임시 버퍼 및 파일의 필요성을 줄일 수 있습니다.

스트림의 current position는 다음 읽기 또는 쓰기 작업이 수행될 위치입니다. 현재 위치는 Seek 메서드를 통해 검색하거나 설정할 수 있습니다. MemoryStream의 새 인스턴스가 만들어지면 현재 위치가 0으로 설정됩니다.

부호 없는 바이트 배열을 사용하여 만든 메모리 스트림에서는 크기 조정 불가능한 데이터 스트림 뷰를 제공하며 쓰기 전용입니다. 바이트 배열을 사용하는 경우에는 생성자에 전달된 매개 변수에 따라 기존 내용을 수정할 수는 있지만 스트림에 추가하거나 스트림을 줄일 수는 없습니다. 빈 메모리 스트림은 크기를 조정할 수 있으며 읽거나 쓸 수 있습니다.

MemoryStream 개체가 ResX 파일이나 .resources 파일에 추가된 경우 런타임에 해당 개체를 검색하려면 GetStream 메서드를 호출합니다.

MemoryStream 개체를 리소스 파일로 serialize할 경우 이 개체는 실제로 UnmanagedMemoryStream으로 serialize됩니다. 이렇게 하면 성능이 향상될 뿐 아니라 Stream 메서드를 통하지 않고도 데이터에 대한 포인터를 직접 가져올 수 있습니다.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE 플랫폼 참고: Windows CE에서는 원래 메모리 스트림의 끝에 바이트가 추가될 수 있기 때문에 클립보드에서 붙여넣은 메모리 스트림의 크기가 클립보드에 복사한 메모리 스트림의 크기보다 약간 클 수 있습니다. 메모리 스트림을 정확하게 검색하려면 개체를 받는 방법을 확인하기 위해 개체 앞에 그 크기를 붙이거나 메모리 스트림과 그 크기에 대한 문자열 값을 포함하여 클립보드에 DataObject를 복사합니다.

예제

다음 코드 예제에서는 메모리를 백업 저장소로 사용하여 데이터를 읽고 쓰는 방법을 보여 줍니다.

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
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}\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);
        }
    }
}
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();
   }
}
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}\n", 
                (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

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

MemoryStream 멤버
System.IO 네임스페이스

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기