Cet article a fait l'objet d'une traduction manuelle. Déplacez votre pointeur sur les phrases de l'article pour voir la version originale de ce texte. |
Traduction
Source
|
StreamReader.Read, méthode
Lit le caractère suivant à partir du flux d'entrée et avance la position d'1 caractère.
Assembly : mscorlib (dans mscorlib.dll)
| Exception | Condition |
|---|---|
| IOException |
Une erreur d'E/S s'est produite. |
Cette méthode substitue Read.
Cette méthode retourne un entier de manière à ce qu'il puisse retourner -1 si la fin du flux a été atteinte. Si vous manipulez la position du flux sous-jacent après avoir lu les données dans la mémoire tampon, la position du flux sous-jacent peut ne pas correspondre à la position de la mémoire tampon interne. Pour réinitialiser la mémoire tampon interne, appelez la méthode DiscardBufferedData ; toutefois, cette méthode ralentit les performances et doit être appelée uniquement en cas d'absolue nécessité.
Pour obtenir la liste des tâches d'E/S courantes, consultez Tâches d'E/S courantes.
L'exemple de code suivant illustre une utilisation simple de la méthode Read.
using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; try { if (File.Exists(path)) { File.Delete(path); } using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("This"); sw.WriteLine("is some text"); sw.WriteLine("to test"); sw.WriteLine("Reading"); } using (StreamReader sr = new StreamReader(path)) { while (sr.Peek() >= 0) { Console.Write((char)sr.Read()); } } } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } }
L'exemple de code suivant illustre la lecture d'un seul caractère à l'aide de la surcharge de la méthode Read() en mettant sous la forme décimale et hexadécimale le résultat de l'entier ASCII.
using System; using System.IO; class StrmRdrRead { public static void Main() { //Create a FileInfo instance representing an existing text file. FileInfo MyFile=new FileInfo(@"c:\csc.txt"); //Instantiate a StreamReader to read from the text file. StreamReader sr=MyFile.OpenText(); //Read a single character. int FirstChar=sr.Read(); //Display the ASCII number of the character read in both decimal and hexadecimal format. Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar); // sr.Close(); } }
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.