Suggérer une traduction
 
Suggestions d'autres utilisateurs :

progress indicator
Aucune autre suggestion.
Cliquez pour évaluer et commenter
MSDN
MSDN Library
Développement .NET
.NET Framework 4
Espaces de noms System.IO
System.IO
StreamReader, classe
Réduire tout/Développer tout Réduire tout
Affichage du contenu :  côte à côteAffichage du contenu : côte à côte
.NET Framework Class Library
StreamReader Class

Implements a TextReader that reads characters from a byte stream in a particular encoding.

System..::.Object
  System..::.MarshalByRefObject
    System.IO..::.TextReader
      System.IO..::.StreamReader

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader _
    Inherits TextReader
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StreamReader : TextReader
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class StreamReader : public TextReader
F#
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type StreamReader =  
    class
        inherit TextReader
    end

The StreamReader type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStreamReader(Stream)Initializes a new instance of the StreamReader class for the specified stream.
Public methodSupported by the XNA FrameworkStreamReader(String)Initializes a new instance of the StreamReader class for the specified file name.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStreamReader(Stream, Boolean)Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStreamReader(Stream, Encoding)Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.
Public methodSupported by the XNA FrameworkStreamReader(String, Boolean)Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.
Public methodSupported by the XNA FrameworkStreamReader(String, Encoding)Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStreamReader(Stream, Encoding, Boolean)Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.
Public methodSupported by the XNA FrameworkStreamReader(String, Encoding, Boolean)Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStreamReader(Stream, Encoding, Boolean, Int32)Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.
Public methodSupported by the XNA FrameworkStreamReader(String, Encoding, Boolean, Int32)Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size.
Top
  NameDescription
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryBaseStreamReturns the underlying stream.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryCurrentEncodingGets the current character encoding that the current StreamReader object is using.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryEndOfStreamGets a value that indicates whether the current stream position is at the end of the stream.
Top
  NameDescription
Public methodSupported by the XNA FrameworkCloseCloses the StreamReader object and the underlying stream, and releases any system resources associated with the reader. (Overrides TextReader..::.Close()()().)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDiscardBufferedDataClears the internal buffer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDispose()()()Releases all resources used by the TextReader object. (Inherited from TextReader.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryDispose(Boolean)Closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources. (Overrides TextReader..::.Dispose(Boolean).)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseClone()()()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryPeekReturns the next available character but does not consume it. (Overrides TextReader..::.Peek()()().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryRead()()()Reads the next character from the input stream and advances the character position by one character. (Overrides TextReader..::.Read()()().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryRead(array<Char>[]()[], Int32, Int32)Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index. (Overrides TextReader..::.Read(array<Char>[]()[], Int32, Int32).)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadBlockReads a maximum of count characters from the current stream, and writes the data to buffer, beginning at index. (Inherited from TextReader.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadLineReads a line of characters from the current stream and returns the data as a string. (Overrides TextReader..::.ReadLine()()().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToEndReads the stream from the current position to the end of the stream. (Overrides TextReader..::.ReadToEnd()()().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryNullA StreamReader object around an empty stream.
Top

StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.

StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system.

By default, a StreamReader is not thread safe. See TextReader..::.Synchronized for a thread-safe wrapper.

The Read(array<Char>[]()[], Int32, Int32) and Write(array<Char>[]()[], Int32, Int32) method overloads read and write the number of characters specified by the count parameter. These are to be distinguished from BufferedStream..::.Read and BufferedStream..::.Write, which read and write the number of bytes specified by the count parameter. Use the BufferedStream methods only for reading and writing an integral number of byte array elements.

NoteNote

When reading from a Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.

For a list of common I/O tasks, see Common I/O Tasks.

The following example uses an instance of StreamReader to read text from a file.

Visual Basic
Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        Try
            ' Create an instance of StreamReader to read from a file.
            Dim sr As StreamReader = New StreamReader("TestFile.txt")
            Dim line As String
            ' Read and display the lines from the file until the end 
            ' of the file is reached.
            Do
                line = sr.ReadLine()
                Console.WriteLine(Line)
            Loop Until line Is Nothing
            sr.Close()
        Catch E As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(E.Message)
        End Try
    End Sub
End Class
C#
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                string line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
Visual C++
using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      StreamReader^ sr = gcnew StreamReader( "TestFile.txt" );
      try
      {
         String^ line;

         // Read and display lines from the file until the end of 
         // the file is reached.
         while ( line = sr->ReadLine() )
         {
            Console::WriteLine( line );
         }
      }
      finally
      {
         if ( sr )
            delete (IDisposable^)sr;
      }
   }
   catch ( Exception^ e ) 
   {
      // Let the user know what went wrong.
      Console::WriteLine( "The file could not be read:" );
      Console::WriteLine( e->Message );
   }
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Bibliothèque de classes .NET Framework
StreamReader, classe

Implémente TextReader qui lit les caractères à partir d'un flux d'octets dans un encodage particulier.

System..::.Object
  System..::.MarshalByRefObject
    System.IO..::.TextReader
      System.IO..::.StreamReader

Espace de noms :  System.IO
Assembly :  mscorlib (dans mscorlib.dll)
Visual Basic
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader _
    Inherits TextReader
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StreamReader : TextReader
VisualC++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class StreamReader : public TextReader
F#
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type StreamReader =  
    class
        inherit TextReader
    end

Le type StreamReader expose les membres suivants.

  NomDescription
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifStreamReader(Stream)Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié.
Méthode publiquePris en charge par XNA FrameworkStreamReader(String)Initialise une nouvelle instance de la classe StreamReader pour le nom de fichier spécifié.
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifStreamReader(Stream, Boolean)Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié, avec l'option de détection de la marque d'ordre d'octet spécifiée.
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifStreamReader(Stream, Encoding)Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié, avec l'encodage de caractères spécifié.
Méthode publiquePris en charge par XNA FrameworkStreamReader(String, Boolean)Initialise une nouvelle instance de la classe StreamReader pour le nom de fichier spécifié, avec l'option de détection de la marque d'ordre d'octet.
Méthode publiquePris en charge par XNA FrameworkStreamReader(String, Encoding)Initialise une nouvelle instance de la classe StreamReader pour le nom de fichier spécifié, avec l'encodage de caractères spécifié.
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifStreamReader(Stream, Encoding, Boolean)Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié, avec l'encodage de caractères spécifiés et l'option de détection de la marque d'ordre d'octet.
Méthode publiquePris en charge par XNA FrameworkStreamReader(String, Encoding, Boolean)Initialise une nouvelle instance de la classe StreamReader pour le nom de fichier spécifié, avec l'encodage de caractères spécifiés et l'option de détection de la marque d'ordre d'octet.
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifStreamReader(Stream, Encoding, Boolean, Int32)Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié, avec l'encodage de caractères spécifiés, l'option de détection de la marque d'ordre d'octet, et la taille de la mémoire tampon.
Méthode publiquePris en charge par XNA FrameworkStreamReader(String, Encoding, Boolean, Int32)Initialise une nouvelle instance de la classe StreamReader pour le nom de fichier spécifié, avec l'encodage de caractères spécifiés, l'option de détection de la marque d'ordre d'octet, et la taille de la mémoire tampon.
Début
  NomDescription
Propriété publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifBaseStreamRetourne le flux sous-jacent.
Propriété publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifCurrentEncodingObtient l'encodage de caractères actuel que l'objet StreamReader actuel utilise.
Propriété publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifEndOfStreamObtient une valeur qui indique si la position actuelle du flux se trouve à la fin du flux.
Début
  NomDescription
Méthode publiquePris en charge par XNA FrameworkCloseFerme l'objet StreamReader et le flux sous-jacent et libère les ressources système associées au lecteur. (Substitue TextReader..::.Close()()().)
Méthode publiqueCreateObjRefCrée un objet contenant toutes les informations appropriées requises pour générer un proxy permettant de communiquer avec un objet distant. (Hérité de MarshalByRefObject.)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifDiscardBufferedDataEfface la mémoire tampon interne.
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifDispose()()()Libère toutes les ressources utilisées par TextReader. (Hérité de TextReader.)
Méthode protégéePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifDispose(Boolean)Ferme le flux sous-jacent, libère les ressources non managées utilisées par StreamReader et libère éventuellement les ressources managées. (Substitue TextReader..::.Dispose(Boolean).)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifEquals(Object)Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.)
Méthode protégéePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifFinalizeAutorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de nettoyage avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifGetHashCodeSert de fonction de hachage pour un type particulier. (Hérité de Object.)
Méthode publiqueGetLifetimeServiceRécupère l'objet de service de durée de vie en cours qui contrôle la stratégie de durée de vie de cette instance. (Hérité de MarshalByRefObject.)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifGetTypeObtient le Type de l'instance actuelle. (Hérité de Object.)
Méthode publiqueInitializeLifetimeServiceObtient un objet de service de durée de vie pour contrôler la stratégie de durée de vie de cette instance. (Hérité de MarshalByRefObject.)
Méthode protégéePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifMemberwiseClone()()()Crée une copie superficielle de l'objet Object actif. (Hérité de Object.)
Méthode protégéeMemberwiseClone(Boolean)Crée une copie superficielle de l'objet MarshalByRefObject actuel. (Hérité de MarshalByRefObject.)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifPeekRetourne le prochain caractère disponible, mais ne le consomme pas. (Substitue TextReader..::.Peek()()().)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifRead()()()Lit le caractère suivant à partir du flux d'entrée et avance la position d'1 caractère. (Substitue TextReader..::.Read()()().)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifRead(array<Char>[]()[], Int32, Int32)Lit un nombre maximum de caractères spécifié du flux de données actuel dans une mémoire tampon, en commençant à l'index spécifié. (Substitue TextReader..::.Read(array<Char>[]()[], Int32, Int32).)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifReadBlockLit un maximum de count caractères à partir du flux actuel, et écrit les données dans buffer, à partir de index. (Hérité de TextReader.)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifReadLineLit une ligne de caractères à partir du flux en cours et retourne les données sous forme de chaîne. (Substitue TextReader..::.ReadLine()()().)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifReadToEndLit le flux entre la position actuelle et la fin du flux. (Substitue TextReader..::.ReadToEnd()()().)
Méthode publiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifToStringRetourne une chaîne qui représente l'objet actuel. (Hérité de Object.)
Début
  NomDescription
Champ publicMembre statiquePris en charge par XNA Framework6aetdk20.PortableClassLibrary(fr-fr,VS.100).gifNullObjet StreamReader autour d'un flux vide.
Début

StreamReader est conçu pour l'entrée de caractères dans un encodage particulier, tandis que la classe Stream est conçue pour l'entrée et la sortie d'octets. Utilisez StreamReader pour lire des lignes d'informations à partir d'un fichier texte standard.

Sauf spécification contraire, l'encodage par défaut de StreamReader est UTF-8, plutôt que la page de codes ANSI par défaut du système actuel. UTF-8 gère correctement les caractères Unicode et fournit des résultats cohérents sur les versions localisées du système d'exploitation.

Par défaut, StreamReader n'est pas thread-safe. Consultez TextReader..::.Synchronized pour plus d'informations sur un wrapper thread-safe.

Les surcharges des méthodes Read(array<Char>[]()[], Int32, Int32) et Write(array<Char>[]()[], Int32, Int32) lisent et écrivent le nombre de caractères spécifiés par le paramètre count. Ils doivent être distingués de BufferedStream..::.Read et BufferedStream..::.Write, qui lisent et écrivent le nombre d'octets spécifié par le paramètre count. Utilisez les méthodes BufferedStream uniquement pour la lecture et l'écriture d'un nombre entier d'éléments du tableau d'octets.

RemarqueRemarque

Lors de la lecture de Stream, il est plus efficace d'utiliser une mémoire tampon de la même taille que la mémoire tampon interne du flux.

Pour obtenir la liste des tâches d'E/S courantes, consultez Tâches d'E/S courantes.

L'exemple suivant utilise une instance de StreamReader pour lire le texte d'un fichier.

Visual Basic
Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        Try
            ' Create an instance of StreamReader to read from a file.
            Dim sr As StreamReader = New StreamReader("TestFile.txt")
            Dim line As String
            ' Read and display the lines from the file until the end 
            ' of the file is reached.
            Do
                line = sr.ReadLine()
                Console.WriteLine(Line)
            Loop Until line Is Nothing
            sr.Close()
        Catch E As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(E.Message)
        End Try
    End Sub
End Class
C#
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                string line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
VisualC++
using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      StreamReader^ sr = gcnew StreamReader( "TestFile.txt" );
      try
      {
         String^ line;

         // Read and display lines from the file until the end of 
         // the file is reached.
         while ( line = sr->ReadLine() )
         {
            Console::WriteLine( line );
         }
      }
      finally
      {
         if ( sr )
            delete (IDisposable^)sr;
      }
   }
   catch ( Exception^ e ) 
   {
      // Let the user know what went wrong.
      Console::WriteLine( "The file could not be read:" );
      Console::WriteLine( e->Message );
   }
}

.NET Framework

Pris en charge dans : 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Pris en charge dans : 4, 3.5 SP1

Pris en charge dans :

Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2

Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Tous les membres static (Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Contenu de la communauté   Qu'est-ce que le Contenu de la communauté ?
Ajouter du contenu RSS  Annotations
Processing
© 2012 Microsoft. Tous droits réservés. Conditions d'utilisation | Marques | Confidentialité
Page view tracker