.NET Framework Class Library StreamReader Class Implements a TextReader that reads characters from a byte stream in a particular encoding.

Inheritance Hierarchy
Namespace:
System.IO
Assembly:
mscorlib (in mscorlib.dll)

Syntax
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader _
Inherits TextReader
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StreamReader : TextReader
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class StreamReader : public TextReader
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type StreamReader =
class
inherit TextReader
end
The StreamReader type exposes the following members.

Constructors
|
| Name | Description |
|---|
.gif) .gif) .gif) | StreamReader(Stream) | Initializes a new instance of the StreamReader class for the specified stream. | .gif) .gif) | StreamReader(String) | Initializes a new instance of the StreamReader class for the specified file name. | .gif) .gif) .gif) | StreamReader(Stream, Boolean) | Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option. | .gif) .gif) .gif) | StreamReader(Stream, Encoding) | Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding. | .gif) .gif) | StreamReader(String, Boolean) | Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option. | .gif) .gif) | StreamReader(String, Encoding) | Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding. | .gif) .gif) .gif) | StreamReader(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. | .gif) .gif) | StreamReader(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. | .gif) .gif) .gif) | StreamReader(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. | .gif) .gif) | StreamReader(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

Methods
|
| Name | Description |
|---|
.gif) .gif) | Close | Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader. (Overrides TextReader..::.Close()()().) | .gif) | CreateObjRef | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) | .gif) .gif) .gif) | DiscardBufferedData | Clears the internal buffer. | .gif) .gif) .gif) | Dispose()()() | Releases all resources used by the TextReader object. (Inherited from TextReader.) | .gif) .gif) .gif) | Dispose(Boolean) | Closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources. (Overrides TextReader..::.Dispose(Boolean).) | .gif) .gif) .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) .gif) .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) .gif) .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | .gif) .gif) .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | .gif) .gif) .gif) | MemberwiseClone()()() | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) | .gif) .gif) .gif) | Peek | Returns the next available character but does not consume it. (Overrides TextReader..::.Peek()()().) | .gif) .gif) .gif) | Read()()() | Reads the next character from the input stream and advances the character position by one character. (Overrides TextReader..::.Read()()().) | .gif) .gif) .gif) | Read(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).) | .gif) .gif) .gif) | ReadBlock | Reads a maximum of count characters from the current stream, and writes the data to buffer, beginning at index. (Inherited from TextReader.) | .gif) .gif) .gif) | ReadLine | Reads a line of characters from the current stream and returns the data as a string. (Overrides TextReader..::.ReadLine()()().) | .gif) .gif) .gif) | ReadToEnd | Reads the stream from the current position to the end of the stream. (Overrides TextReader..::.ReadToEnd()()().) | .gif) .gif) .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | Top

Remarks
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. Note |
|---|
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.

Examples
The following example uses an instance of StreamReader to read text from a file.
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
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);
}
}
}
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 );
}
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

Platforms
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.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
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.

Hiérarchie d'héritage
Espace de noms :
System.IO
Assembly :
mscorlib (dans mscorlib.dll)

Syntaxe
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader _
Inherits TextReader
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StreamReader : TextReader
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class StreamReader : public TextReader
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type StreamReader =
class
inherit TextReader
end
Le type StreamReader expose les membres suivants.

Constructeurs
|
| Nom | Description |
|---|
.gif) .gif) .gif) | StreamReader(Stream) | Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié. | .gif) .gif) | StreamReader(String) | Initialise une nouvelle instance de la classe StreamReader pour le nom de fichier spécifié. | .gif) .gif) .gif) | StreamReader(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. | .gif) .gif) .gif) | StreamReader(Stream, Encoding) | Initialise une nouvelle instance de la classe StreamReader pour le flux spécifié, avec l'encodage de caractères spécifié. | .gif) .gif) | StreamReader(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. | .gif) .gif) | StreamReader(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é. | .gif) .gif) .gif) | StreamReader(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. | .gif) .gif) | StreamReader(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. | .gif) .gif) .gif) | StreamReader(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. | .gif) .gif) | StreamReader(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

Méthodes

Notes
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. Remarque |
|---|
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.

Exemples
L'exemple suivant utilise une instance de StreamReader pour lire le texte d'un fichier.
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
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);
}
}
}
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 );
}
}

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfilePris en charge dans : 4, 3.5 SP1 Pris en charge dans :

Plateformes
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.

Sécurité des threads
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.

Voir aussi
RéférenceAutres ressources
|