Cliquez pour évaluer et commenter
MSDN
MSDN Library
Développement .NET
Versions précédentes
.NET Framework SDK 2.0
Class Library Reference
System.IO
MemoryStream, classe
Réduire tout/Développer tout Réduire tout
Cette page est spécifique à
Microsoft Visual Studio 2005/.NET Framework 2.0

D'autres versions sont également disponibles pour :
Bibliothèque de classes .NET Framework
MemoryStream, classe

Crée un flux ayant pour mémoire un magasin de sauvegarde.

Espace de noms : System.IO
Assembly : mscorlib (dans mscorlib.dll)

Visual Basic (Déclaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class MemoryStream
    Inherits Stream
Visual Basic (Utilisation)
Dim instance As MemoryStream
C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class MemoryStream : Stream
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class MemoryStream : public Stream
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class MemoryStream extends Stream
JScript
SerializableAttribute 
ComVisibleAttribute(true) 
public class MemoryStream extends Stream

Pour obtenir un exemple de création de fichier et d'écriture de texte dans un fichier, consultez Comment : écrire du texte dans un fichier. Pour obtenir un exemple de lecture de texte à partir d'un fichier, consultez Comment : lire du texte dans un fichier. Pour obtenir un exemple de lecture et d'écriture dans un fichier binaire, consultez Comment : lire et écrire dans un fichier de données créé récemment.

La classe MemoryStream crée des flux dotés d'une mémoire sous la forme d'un magasin de sauvegarde au lieu d'un disque ou d'une connexion réseau. MemoryStream encapsule les données stockées sous la forme d'un tableau d'octets non signés qui est initialisé lors de la création d'un objet MemoryStream. Le tableau créé peut également être vide. Les données encapsulées sont directement accessibles dans la mémoire. Les flux de mémoire peuvent réduire le recours à des mémoires tampons et à des fichiers temporaires dans une application.

Le current position d'un flux est la position à laquelle doit avoir lieu la prochaine opération de lecture ou d'écriture. La position actuelle peut être récupérée ou définie à l'aide de la méthode Seek. Lorsqu'une nouvelle instance de MemoryStream est créée, la position actuelle a la valeur zéro.

Les flux de mémoire créés à partir d'un tableau d'octets non signés fournissent un affichage des données sous la forme d'un flux non redimensionnable. Ils sont uniquement accessibles en écriture. Lors de l'utilisation d'un tableau d'octets, il n'est pas possible d'ajouter des données au flux ou de réduire sa taille, mais dans certains cas, vous pourrez modifier le contenu existant, selon les paramètres passés au constructeur. Les flux de mémoire vides sont redimensionnables et ils sont accessibles en lecture et en écriture.

Si un objet MemoryStream est ajouté à un fichier ResX ou à un fichier .resources, appelez la méthode GetStream au moment de l'exécution pour le récupérer.

Si un objet MemoryStream est sérialisé en tant que fichier de ressources, il sera en fait sérialisé en tant que UnmanagedMemoryStream. Ce comportement fournit de meilleures performances, ainsi que la possibilité d'obtenir directement un pointeur vers les données sans devoir passer par les méthodes Stream.

Remarque sur la plate-forme Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows CE : Dans Windows CE, un flux de mémoire collé à partir du Presse-papiers peut avoir une taille légèrement supérieure à celle du flux de mémoire copié vers le Presse-papiers, car des octets supplémentaires peuvent être ajoutés à la fin du flux de mémoire d'origine. Pour récupérer correctement le flux de mémoire, faites précéder l'objet de sa taille pour déterminer comment le recevoir ou copiez DataObject vers le Presse-papiers contenant le flux de mémoire et une valeur de chaîne de sa taille.

L'exemple de code suivant montre comment lire et écrire des données en utilisant la mémoire comme magasin de sauvegarde.

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}\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);
        }
    }
}
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}\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();
   }
}
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}\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
Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0, 1.0
Contenu de la communauté   Qu'est-ce que le Contenu de la communauté ?
Ajouter du contenu RSS  Annotations
Processing
© 2010 Microsoft Corporation. Tous droits réservés. Conditions d'utilisation | Marques | Confidentialité
Page view tracker