Classe StreamReader (System.IO)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Classe StreamReader

Implementa un oggetto TextReader che legge i caratteri da un flusso di byte in una particolare codifica.

Spazio dei nomi: System.IO
Assembly: mscorlib (in mscorlib.dll)

Sintassi

Visual Basic - (Dichiarazione)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader
	Inherits TextReader
Visual Basic (Utilizzo)
Dim instance As StreamReader

C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class StreamReader : TextReader
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class StreamReader : public TextReader
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class StreamReader extends TextReader
JScript
SerializableAttribute 
ComVisibleAttribute(true) 
public class StreamReader extends TextReader
Note

StreamReader è progettato per l'input di caratteri in una particolare codifica, mentre la classe Stream è progettata per l'input e l'output dei byte. Utilizzare StreamReader per leggere righe di informazioni da un file di testo standard.

L'impostazione predefinita di StreamReader è la codifica UTF-8 se non diversamente specificato, anziché la tabella codici ANSI per il sistema corrente. Il formato UTF-8 gestisce i caratteri Unicode in modo corretto e fornisce risultati coerenti sulle versioni localizzate del sistema operativo.

Per impostazione predefinita, StreamReader non è thread-safe. Per un wrapper thread-safe, vedere TextReader.Synchronized.

Gli overload del metodo Read(Char[],Int32,Int32) e del metodo Write(Char[],Int32,Int32) leggono e scrivono il numero di caratteri specificato dal parametro count. Devono essere distinti da BufferedStream.Read e da BufferedStream.Write, che leggono e scrivono il numero di byte specificati dal parametro count. Utilizzare i metodi BufferedStream solo per la lettura e la scrittura di un numero integrale di elementi di matrice di byte.

NotaNota

Quando si esegue la lettura da un oggetto Stream, è preferibile utilizzare un buffer delle stesse dimensioni del buffer interno del flusso.

Per un esempio sull'utilizzo di questa classe, vedere la sezione Esempio. Nella tabella che segue vengono elencati esempi di altre attività di I/O tipiche o correlate.

Per eseguire questa operazione...

Vedere l'esempio in questo argomento...

Creazione di un file di testo.

Procedura: scrivere testo su un file

Scrittura in un file di testo.

Procedura: scrivere testo su un file

Lettura da un file di testo.

Procedura: leggere testo da un file

Aggiunta di testo a un file.

Procedura: aprire e accodare un file di log

File.AppendText

FileInfo.AppendText

Acquisizione della dimensione di un file.

FileInfo.Length

Acquisizione degli attributi di un file.

File.GetAttributes

Impostazione degli attributi di un file.

File.SetAttributes

Determinazione dell'esistenza di un file.

File.Exists

Lettura da un file binario.

Procedura: leggere e scrivere su un file di dati appena creato

Scrittura in un file binario.

Procedura: leggere e scrivere su un file di dati appena creato

Esempio

Nell'esempio di codice riportato di seguito viene utilizzato un oggetto StreamReader per leggere testo da un 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);
        }
    }
}

C++
using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      // The using statement also closes the StreamReader.
      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 );
   }
}

J#
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        try {            
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            StreamReader sr = new 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()) != null) {
                    Console.WriteLine(line);
                }
            }
            finally {
                sr.Dispose();
            }            
        }
        catch (System.Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.get_Message());
        }
    } //main
} //Test

Gerarchia di ereditarietà

System.Object
   System.MarshalByRefObject
     System.IO.TextReader
      System.IO.StreamReader
Codice thread safe

I membri statici pubblici (Shared in Visual Basic) di questo tipo sono validi per le operazioni multithreading. I membri di istanza non sono garantiti come thread safe.
Piattaforme

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

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.

Informazioni sulla versione

.NET Framework

Supportato in: 2.0 1.1 1.0

.NET Compact Framework

Supportato in: 2.0 1.0
Vedere anche