StreamReader Constructores

Definición

Inicializa una nueva instancia de la clase StreamReader para el flujo especificado.Initializes a new instance of the StreamReader class for the specified stream.

Sobrecargas

StreamReader(Stream)

Inicializa una nueva instancia de la clase StreamReader para el flujo especificado.Initializes a new instance of the StreamReader class for the specified stream.

StreamReader(String)

Inicializa una nueva instancia de la clase StreamReader para el nombre de archivo especificado.Initializes a new instance of the StreamReader class for the specified file name.

StreamReader(Stream, Boolean)

Inicializa una nueva instancia de la clase StreamReader para la secuencia especificada, con la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.

StreamReader(Stream, Encoding)

Inicializa una nueva instancia de la clase StreamReader para la secuencia especificada y con la codificación de caracteres indicada.Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.

StreamReader(String, Boolean)

Inicializa una nueva instancia de la clase StreamReader para el nombre de archivo especificado, con la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.

StreamReader(String, Encoding)

Inicializa una nueva instancia de la clase StreamReader para el nombre de archivo especificado y con la codificación de caracteres indicada.Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.

StreamReader(Stream, Encoding, Boolean)

Inicializa una nueva instancia de la clase StreamReader de la secuencia especificada, con la codificación de caracteres especificada y la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.

StreamReader(String, Encoding, Boolean)

Inicializa una nueva instancia de la clase StreamReader del nombre de archivo especificado, con la codificación de caracteres especificada y la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.

StreamReader(Stream, Encoding, Boolean, Int32)

Inicializa una nueva instancia de la clase StreamReader de la secuencia especificada, con la codificación de caracteres especificada, la opción especificada de detección de marcas de orden de bytes y el tamaño del búfer.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.

StreamReader(String, Encoding, Boolean, Int32)

Inicializa una nueva instancia de la clase StreamReader del nombre de archivo especificado, con la codificación de caracteres especificada, la opción especificada de detección de marcas de orden de bytes y el tamaño del búfer.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.

StreamReader(Stream, Encoding, Boolean, Int32, Boolean)

Inicializa una nueva instancia de la clase StreamReader de la secuencia especificada basada en la codificación de caracteres especificada, la opción especificada de detección de marcas de orden de bytes y el tamaño del búfer y, opcionalmente, deja abierta la secuencia.Initializes a new instance of the StreamReader class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.

StreamReader(Stream)

Inicializa una nueva instancia de la clase StreamReader para el flujo especificado.Initializes a new instance of the StreamReader class for the specified stream.

public:
 StreamReader(System::IO::Stream ^ stream);
public StreamReader (System.IO.Stream stream);
new System.IO.StreamReader : System.IO.Stream -> System.IO.StreamReader
Public Sub New (stream As Stream)

Parámetros

stream
Stream

Secuencia que se va a leer.The stream to be read.

Excepciones

stream no es compatible con la lectura.stream does not support reading.

stream es null.stream is null.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      FileStream^ fs = gcnew FileStream( path,FileMode::Open );
      try
      {
         StreamReader^ sr = gcnew StreamReader( fs );
         try
         {
            while ( sr->Peek() >= 0 )
            {
               Console::WriteLine( sr->ReadLine() );
            }
         }
         finally
         {
            delete sr;
         }
      }
      finally
      {
         delete fs;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
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(new FileStream(path, FileMode.CreateNew)))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("reading");
            }

            using (StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open)))
            {
                while (sr.Peek() >= 0)
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim fs As FileStream = New FileStream(path, FileMode.Open)

            Dim sr As StreamReader = New StreamReader(fs)

            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
            fs.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentarios

Este constructor inicializa la codificación en UTF8Encoding , la BaseStream propiedad utilizando el stream parámetro y el tamaño de búfer interno en 1024 bytes.This constructor initializes the encoding to UTF8Encoding, the BaseStream property using the stream parameter, and the internal buffer size to 1024 bytes.

El StreamReader objeto llama a Dispose() en el Stream objeto proporcionado cuando StreamReader.Dispose se llama a.The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

StreamReader(String)

Inicializa una nueva instancia de la clase StreamReader para el nombre de archivo especificado.Initializes a new instance of the StreamReader class for the specified file name.

public:
 StreamReader(System::String ^ path);
public StreamReader (string path);
new System.IO.StreamReader : string -> System.IO.StreamReader
Public Sub New (path As String)

Parámetros

path
String

Ruta de acceso completa del archivo que debe leerse.The complete file path to be read.

Excepciones

path es una cadena vacía ("").path is an empty string ("").

path es null.path is null.

No se encuentra el archivo.The file cannot be found.

La ruta de acceso especificada no es válida, por ejemplo, está en una unidad no asignada.The specified path is invalid, such as being on an unmapped drive.

path incluye una sintaxis incorrecta o no válida para el nombre del archivo, el nombre del directorio o la etiqueta de volumen.path includes an incorrect or invalid syntax for file name, directory name, or volume label.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         while ( sr->Peek() >= 0 )
         {
            Console::WriteLine( sr->ReadLine() );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
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.WriteLine(sr.ReadLine());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentarios

La ruta de acceso completa del archivo se especifica mediante el path parámetro.The complete file path is specified by the path parameter. Este constructor inicializa la codificación en UTF8Encoding y el tamaño del búfer en 1024 bytes.This constructor initializes the encoding to UTF8Encoding and the buffer size to 1024 bytes.

El path parámetro puede ser un nombre de archivo, incluido un archivo en un recurso compartido de Convención de nomenclatura universal (UNC).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

pathNo es necesario que el parámetro sea un archivo almacenado en disco; puede ser cualquier parte de un sistema que admita el acceso mediante secuencias.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(Stream, Boolean)

Inicializa una nueva instancia de la clase StreamReader para la secuencia especificada, con la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.

public:
 StreamReader(System::IO::Stream ^ stream, bool detectEncodingFromByteOrderMarks);
public StreamReader (System.IO.Stream stream, bool detectEncodingFromByteOrderMarks);
new System.IO.StreamReader : System.IO.Stream * bool -> System.IO.StreamReader
Public Sub New (stream As Stream, detectEncodingFromByteOrderMarks As Boolean)

Parámetros

stream
Stream

Secuencia que se va a leer.The stream to be read.

detectEncodingFromByteOrderMarks
Boolean

Indica si se deben buscar marcas de orden de byte al comienzo del archivo.Indicates whether to look for byte order marks at the beginning of the file.

Excepciones

stream no es compatible con la lectura.stream does not support reading.

stream es null.stream is null.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

Este constructor inicializa la codificación en UTF8Encoding , la BaseStream propiedad utilizando el stream parámetro y el tamaño de búfer interno en 1024 bytes.This constructor initializes the encoding to UTF8Encoding, the BaseStream property using the stream parameter, and the internal buffer size to 1024 bytes.

El detectEncodingFromByteOrderMarks parámetro detecta la codificación examinando los primeros cuatro bytes de la secuencia.The detectEncodingFromByteOrderMarks parameter detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El StreamReader objeto llama a Dispose() en el Stream objeto proporcionado cuando StreamReader.Dispose se llama a.The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

StreamReader(Stream, Encoding)

Inicializa una nueva instancia de la clase StreamReader para la secuencia especificada y con la codificación de caracteres indicada.Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.

public:
 StreamReader(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding);
public StreamReader (System.IO.Stream stream, System.Text.Encoding encoding);
new System.IO.StreamReader : System.IO.Stream * System.Text.Encoding -> System.IO.StreamReader
Public Sub New (stream As Stream, encoding As Encoding)

Parámetros

stream
Stream

Secuencia que se va a leer.The stream to be read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

Excepciones

stream no es compatible con la lectura.stream does not support reading.

stream o encoding es null.stream or encoding is null.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

La codificación de caracteres se establece mediante el encoding parámetro y el tamaño del búfer se establece en 1024 bytes.The character encoding is set by the encoding parameter, and the buffer size is set to 1024 bytes. El StreamReader objeto intenta detectar la codificación examinando los primeros cuatro bytes de la secuencia.The StreamReader object attempts to detect the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El StreamReader objeto llama a Dispose() en el Stream objeto proporcionado cuando StreamReader.Dispose se llama a.The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(String, Boolean)

Inicializa una nueva instancia de la clase StreamReader para el nombre de archivo especificado, con la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.

public:
 StreamReader(System::String ^ path, bool detectEncodingFromByteOrderMarks);
public StreamReader (string path, bool detectEncodingFromByteOrderMarks);
new System.IO.StreamReader : string * bool -> System.IO.StreamReader
Public Sub New (path As String, detectEncodingFromByteOrderMarks As Boolean)

Parámetros

path
String

Ruta de acceso completa del archivo que debe leerse.The complete file path to be read.

detectEncodingFromByteOrderMarks
Boolean

Indica si se deben buscar marcas de orden de byte al comienzo del archivo.Indicates whether to look for byte order marks at the beginning of the file.

Excepciones

path es una cadena vacía ("").path is an empty string ("").

path es null.path is null.

No se encuentra el archivo.The file cannot be found.

La ruta de acceso especificada no es válida, por ejemplo, está en una unidad no asignada.The specified path is invalid, such as being on an unmapped drive.

path incluye una sintaxis incorrecta o no válida para el nombre del archivo, el nombre del directorio o la etiqueta de volumen.path includes an incorrect or invalid syntax for file name, directory name, or volume label.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

Este constructor inicializa la codificación en UTF8Encoding , la BaseStream propiedad utilizando el stream parámetro y el tamaño de búfer interno en 1024 bytes.This constructor initializes the encoding to UTF8Encoding, the BaseStream property using the stream parameter, and the internal buffer size to 1024 bytes.

El path parámetro puede ser un nombre de archivo, incluido un archivo en un recurso compartido de Convención de nomenclatura universal (UNC).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

pathNo es necesario que el parámetro sea un archivo almacenado en disco; puede ser cualquier parte de un sistema que admita el acceso mediante secuencias.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

El detectEncodingFromByteOrderMarks parámetro detecta la codificación examinando los primeros cuatro bytes de la secuencia.The detectEncodingFromByteOrderMarks parameter detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, UTF8Encoding se utiliza.Otherwise, the UTF8Encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

StreamReader(String, Encoding)

Inicializa una nueva instancia de la clase StreamReader para el nombre de archivo especificado y con la codificación de caracteres indicada.Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.

public:
 StreamReader(System::String ^ path, System::Text::Encoding ^ encoding);
public StreamReader (string path, System.Text.Encoding encoding);
new System.IO.StreamReader : string * System.Text.Encoding -> System.IO.StreamReader
Public Sub New (path As String, encoding As Encoding)

Parámetros

path
String

Ruta de acceso completa del archivo que debe leerse.The complete file path to be read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

Excepciones

path es una cadena vacía ("").path is an empty string ("").

path o encoding es null.path or encoding is null.

No se encuentra el archivo.The file cannot be found.

La ruta de acceso especificada no es válida, por ejemplo, está en una unidad no asignada.The specified path is invalid, such as being on an unmapped drive.

path incluye una sintaxis incorrecta o no válida para el nombre del archivo, el nombre del directorio o la etiqueta de volumen.path includes an incorrect or invalid syntax for file name, directory name, or volume label.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

Este constructor inicializa la codificación especificada por el encoding parámetro y el tamaño del búfer interno en 1024 bytes.This constructor initializes the encoding as specified by the encoding parameter, and the internal buffer size to 1024 bytes. El StreamReader objeto intenta detectar la codificación examinando los primeros cuatro bytes de la secuencia.The StreamReader object attempts to detect the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El path parámetro puede ser un nombre de archivo, incluido un archivo en un recurso compartido de Convención de nomenclatura universal (UNC).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

pathNo es necesario que el parámetro sea un archivo almacenado en disco; puede ser cualquier parte de un sistema que admita el acceso mediante secuencias.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(Stream, Encoding, Boolean)

Inicializa una nueva instancia de la clase StreamReader de la secuencia especificada, con la codificación de caracteres especificada y la opción especificada de detección de marcas de orden de bytes.Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.

public:
 StreamReader(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding, bool detectEncodingFromByteOrderMarks);
public StreamReader (System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks);
new System.IO.StreamReader : System.IO.Stream * System.Text.Encoding * bool -> System.IO.StreamReader
Public Sub New (stream As Stream, encoding As Encoding, detectEncodingFromByteOrderMarks As Boolean)

Parámetros

stream
Stream

Secuencia que se va a leer.The stream to be read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

detectEncodingFromByteOrderMarks
Boolean

Indica si se deben buscar marcas de orden de byte al comienzo del archivo.Indicates whether to look for byte order marks at the beginning of the file.

Excepciones

stream no es compatible con la lectura.stream does not support reading.

stream o encoding es null.stream or encoding is null.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

Este constructor inicializa la codificación tal y como se especifica en el encoding parámetro, la BaseStream propiedad utilizando el stream parámetro y el tamaño de búfer interno en 1024 bytes.This constructor initializes the encoding as specified by the encoding parameter, the BaseStream property using the stream parameter, and the internal buffer size to 1024 bytes.

El detectEncodingFromByteOrderMarks parámetro detecta la codificación examinando los primeros cuatro bytes de la secuencia.The detectEncodingFromByteOrderMarks parameter detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El StreamReader objeto llama a Dispose() en el Stream objeto proporcionado cuando StreamReader.Dispose se llama a.The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(String, Encoding, Boolean)

Inicializa una nueva instancia de la clase StreamReader del nombre de archivo especificado, con la codificación de caracteres especificada y la opción especificada de detección de marcas de orden de bytes.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:
 StreamReader(System::String ^ path, System::Text::Encoding ^ encoding, bool detectEncodingFromByteOrderMarks);
public StreamReader (string path, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks);
new System.IO.StreamReader : string * System.Text.Encoding * bool -> System.IO.StreamReader
Public Sub New (path As String, encoding As Encoding, detectEncodingFromByteOrderMarks As Boolean)

Parámetros

path
String

Ruta de acceso completa del archivo que debe leerse.The complete file path to be read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

detectEncodingFromByteOrderMarks
Boolean

Indica si se deben buscar marcas de orden de byte al comienzo del archivo.Indicates whether to look for byte order marks at the beginning of the file.

Excepciones

path es una cadena vacía ("").path is an empty string ("").

path o encoding es null.path or encoding is null.

No se encuentra el archivo.The file cannot be found.

La ruta de acceso especificada no es válida, por ejemplo, está en una unidad no asignada.The specified path is invalid, such as being on an unmapped drive.

path incluye una sintaxis incorrecta o no válida para el nombre del archivo, el nombre del directorio o la etiqueta de volumen.path includes an incorrect or invalid syntax for file name, directory name, or volume label.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

Este constructor inicializa la codificación especificada por el encoding parámetro y el tamaño del búfer interno en 1024 bytes.This constructor initializes the encoding as specified by the encoding parameter, and the internal buffer size to 1024 bytes.

El detectEncodingFromByteOrderMarks parámetro detecta la codificación examinando los primeros cuatro bytes de la secuencia.The detectEncodingFromByteOrderMarks parameter detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El path parámetro puede ser un nombre de archivo, incluido un archivo en un recurso compartido de Convención de nomenclatura universal (UNC).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

pathNo es necesario que el parámetro sea un archivo almacenado en disco; puede ser cualquier parte de un sistema que admita el acceso mediante secuencias.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(Stream, Encoding, Boolean, Int32)

Inicializa una nueva instancia de la clase StreamReader de la secuencia especificada, con la codificación de caracteres especificada, la opción especificada de detección de marcas de orden de bytes y el tamaño del búfer.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:
 StreamReader(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding, bool detectEncodingFromByteOrderMarks, int bufferSize);
public StreamReader (System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize);
new System.IO.StreamReader : System.IO.Stream * System.Text.Encoding * bool * int -> System.IO.StreamReader
Public Sub New (stream As Stream, encoding As Encoding, detectEncodingFromByteOrderMarks As Boolean, bufferSize As Integer)

Parámetros

stream
Stream

Secuencia que se va a leer.The stream to be read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

detectEncodingFromByteOrderMarks
Boolean

Indica si se deben buscar marcas de orden de byte al comienzo del archivo.Indicates whether to look for byte order marks at the beginning of the file.

bufferSize
Int32

Tamaño mínimo de búfer.The minimum buffer size.

Excepciones

La secuencia no admite lectura.The stream does not support reading.

stream o encoding es null.stream or encoding is null.

bufferSize es menor o igual que cero.bufferSize is less than or equal to zero.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

El tamaño del búfer, en número de caracteres de 16 bits, se establece mediante el bufferSize parámetro.The buffer size, in number of 16-bit characters, is set by the bufferSize parameter. Si bufferSize es menor que el tamaño mínimo permitido (128 caracteres), se usa el tamaño mínimo permitido.If bufferSize is less than the minimum allowable size (128 characters), the minimum allowable size is used.

Este constructor permite cambiar la codificación la primera vez que se lee desde el StreamReader objeto.This constructor allows you to change the encoding the first time you read from the StreamReader object. El detectEncodingFromByteOrderMarks parámetro detecta la codificación examinando los primeros cuatro bytes de la secuencia.The detectEncodingFromByteOrderMarks parameter detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El StreamReader objeto llama a Dispose() en el Stream objeto proporcionado cuando StreamReader.Dispose se llama a.The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.

Nota

Al leer desde un Stream , es más eficaz utilizar un búfer que tenga el mismo tamaño que el búfer interno de la secuencia.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.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(String, Encoding, Boolean, Int32)

Inicializa una nueva instancia de la clase StreamReader del nombre de archivo especificado, con la codificación de caracteres especificada, la opción especificada de detección de marcas de orden de bytes y el tamaño del búfer.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.

public:
 StreamReader(System::String ^ path, System::Text::Encoding ^ encoding, bool detectEncodingFromByteOrderMarks, int bufferSize);
public StreamReader (string path, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize);
new System.IO.StreamReader : string * System.Text.Encoding * bool * int -> System.IO.StreamReader
Public Sub New (path As String, encoding As Encoding, detectEncodingFromByteOrderMarks As Boolean, bufferSize As Integer)

Parámetros

path
String

Ruta de acceso completa del archivo que debe leerse.The complete file path to be read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

detectEncodingFromByteOrderMarks
Boolean

Indica si se deben buscar marcas de orden de byte al comienzo del archivo.Indicates whether to look for byte order marks at the beginning of the file.

bufferSize
Int32

Tamaño mínimo del búfer expresado en número de caracteres de 16 bits.The minimum buffer size, in number of 16-bit characters.

Excepciones

path es una cadena vacía ("").path is an empty string ("").

path o encoding es null.path or encoding is null.

No se encuentra el archivo.The file cannot be found.

La ruta de acceso especificada no es válida, por ejemplo, está en una unidad no asignada.The specified path is invalid, such as being on an unmapped drive.

path incluye una sintaxis incorrecta o no válida para el nombre del archivo, el nombre del directorio o la etiqueta de volumen.path includes an incorrect or invalid syntax for file name, directory name, or volume label.

buffersize es menor o igual que cero.buffersize is less than or equal to zero.

Ejemplos

En el ejemplo de código siguiente se muestra este StreamReader constructor.The following code example demonstrates this StreamReader constructor.

void getNewStreamReader()
{
   
   //Get a new StreamReader in ASCII format from a
   //file using a buffer and byte order mark detection
   StreamReader^ srAsciiFromFileFalse512 = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //file with byte order mark detection = false
   StreamReader^ srAsciiFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a file 
   StreamReader^ srAsciiFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt",System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //file with byte order mark detection = false
   StreamReader^ srFromFileFalse = gcnew StreamReader(  "C:\\Temp\\Test.txt",false );
   
   //Get a new StreamReader from a file
   StreamReader^ srFromFile = gcnew StreamReader(  "C:\\Temp\\Test.txt" );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false and a buffer
   StreamReader^ srAsciiFromStreamFalse512 = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false,512 );
   
   //Get a new StreamReader in ASCII format from a
   //FileStream with byte order mark detection = false
   StreamReader^ srAsciiFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII,false );
   
   //Get a new StreamReader in ASCII format from a FileStream
   StreamReader^ srAsciiFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),System::Text::Encoding::ASCII );
   
   //Get a new StreamReader from a
   //FileStream with byte order mark detection = false
   StreamReader^ srFromStreamFalse = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ),false );
   
   //Get a new StreamReader from a FileStream
   StreamReader^ srFromStream = gcnew StreamReader( File::OpenRead(  "C:\\Temp\\Test.txt" ) );
}


private void getNewStreamReader()
{
    //Get a new StreamReader in ASCII format from a
    //file using a buffer and byte order mark detection
    StreamReader srAsciiFromFileFalse512 =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //file with byte order mark detection = false
    StreamReader srAsciiFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a file
    StreamReader srAsciiFromFile =
        new StreamReader("C:\\Temp\\Test.txt",
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //file with byte order mark detection = false
    StreamReader srFromFileFalse =
        new StreamReader("C:\\Temp\\Test.txt", false);
    //Get a new StreamReader from a file
    StreamReader srFromFile =
        new StreamReader("C:\\Temp\\Test.txt");
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false and a buffer
    StreamReader srAsciiFromStreamFalse512 = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false, 512);
    //Get a new StreamReader in ASCII format from a
    //FileStream with byte order mark detection = false
    StreamReader srAsciiFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII, false);
    //Get a new StreamReader in ASCII format from a FileStream
    StreamReader srAsciiFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        System.Text.Encoding.ASCII);
    //Get a new StreamReader from a
    //FileStream with byte order mark detection = false
    StreamReader srFromStreamFalse = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),
        false);
    //Get a new StreamReader from a FileStream
    StreamReader srFromStream = new StreamReader(
        (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"));
}
Private Sub getNewStreamReader()
    Dim S As Stream = File.OpenRead("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'file using a buffer and byte order mark detection
    Dim SrAsciiFromFileFalse512 As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'file with byte order mark detection = false
    Dim SrAsciiFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a file 
    Dim SrAsciiFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt", _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'file with byte order mark detection = false        
    Dim SrFromFileFalse As StreamReader = New StreamReader("C:\Temp\Test.txt", False)
    'Get a new StreamReader from a file
    Dim SrFromFile As StreamReader = New StreamReader("C:\Temp\Test.txt")
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false and a buffer
    Dim SrAsciiFromStreamFalse512 As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII, False, 512)
    'Get a new StreamReader in ASCII format from a
    'FileStream with byte order mark detection = false
    Dim SrAsciiFromStreamFalse = New StreamReader(S, _
        System.Text.Encoding.ASCII, False)
    'Get a new StreamReader in ASCII format from a FileStream
    Dim SrAsciiFromStream As StreamReader = New StreamReader(S, _
        System.Text.Encoding.ASCII)
    'Get a new StreamReader from a
    'FileStream with byte order mark detection = false
    Dim SrFromStreamFalse As StreamReader = New StreamReader(S, False)
    'Get a new StreamReader from a FileStream
    Dim SrFromStream As StreamReader = New StreamReader(S)

End Sub

Comentarios

Este constructor inicializa la codificación tal y como se especifica en el encoding parámetro.This constructor initializes the encoding as specified by the encoding parameter.

Este constructor permite cambiar la codificación la primera vez que se lee desde el StreamReader objeto.This constructor allows you to change the encoding the first time you read from the StreamReader object. El detectEncodingFromByteOrderMarks parámetro detecta la codificación examinando los primeros cuatro bytes de la secuencia.The detectEncodingFromByteOrderMarks parameter detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

El tamaño del búfer, en número de caracteres de 16 bits, se establece mediante el bufferSize parámetro.The buffer size, in number of 16-bit characters, is set by the bufferSize parameter. Si bufferSize es menor que el tamaño mínimo permitido (128 caracteres), se usa el tamaño mínimo permitido.If bufferSize is less than the minimum allowable size (128 characters), the minimum allowable size is used.

El path parámetro puede ser un nombre de archivo, incluido un archivo en un recurso compartido de Convención de nomenclatura universal (UNC).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

pathNo es necesario que el parámetro sea un archivo almacenado en disco; puede ser cualquier parte de un sistema que admita el acceso mediante secuencias.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se puedan interpretar y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

StreamReader(Stream, Encoding, Boolean, Int32, Boolean)

Inicializa una nueva instancia de la clase StreamReader de la secuencia especificada basada en la codificación de caracteres especificada, la opción especificada de detección de marcas de orden de bytes y el tamaño del búfer y, opcionalmente, deja abierta la secuencia.Initializes a new instance of the StreamReader class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.

public:
 StreamReader(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen);
public StreamReader (System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen);
public StreamReader (System.IO.Stream stream, System.Text.Encoding? encoding = default, bool detectEncodingFromByteOrderMarks = true, int bufferSize = -1, bool leaveOpen = false);
new System.IO.StreamReader : System.IO.Stream * System.Text.Encoding * bool * int * bool -> System.IO.StreamReader
Public Sub New (stream As Stream, encoding As Encoding, detectEncodingFromByteOrderMarks As Boolean, bufferSize As Integer, leaveOpen As Boolean)
Public Sub New (stream As Stream, Optional encoding As Encoding = Nothing, Optional detectEncodingFromByteOrderMarks As Boolean = true, Optional bufferSize As Integer = -1, Optional leaveOpen As Boolean = false)

Parámetros

stream
Stream

Secuencia que se va a leer.The stream to read.

encoding
Encoding

Codificación de caracteres que se utilizará.The character encoding to use.

detectEncodingFromByteOrderMarks
Boolean

Es true para buscar marcas de orden de byte al comienzo del archivo; en caso contrario, es false.true to look for byte order marks at the beginning of the file; otherwise, false.

bufferSize
Int32

Tamaño mínimo de búfer.The minimum buffer size.

leaveOpen
Boolean

true para dejar el flujo abierto después de desechar el objeto StreamReader; de lo contrario, false.true to leave the stream open after the StreamReader object is disposed; otherwise, false.

Comentarios

A menos que establezca el leaveOpen parámetro en true , el StreamReader objeto llama a Dispose() en el objeto proporcionado Stream cuando StreamReader.Dispose se llama a.Unless you set the leaveOpen parameter to true, the StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.

El tamaño del búfer, en número de caracteres de 16 bits, se establece mediante el bufferSize parámetro.The buffer size, in number of 16-bit characters, is set by the bufferSize parameter. Si bufferSize es menor que el tamaño mínimo permitido (128 caracteres), se usa el tamaño mínimo permitido.If bufferSize is less than the minimum allowable size (128 characters), the minimum allowable size is used.

Este constructor permite cambiar la codificación la primera vez que se lee desde el StreamReader objeto.This constructor enables you to change the encoding the first time you read from the StreamReader object. Si el detectEncodingFromByteOrderMarks parámetro es true , el constructor detecta la codificación examinando los primeros cuatro bytes de la secuencia.If the detectEncodingFromByteOrderMarks parameter is true, the constructor detects the encoding by looking at the first four bytes of the stream. Reconoce automáticamente el texto UTF-8, Little-Endian Unicode, Unicode big-endian, UTF-32 y Big-Endian UTF-32 si el archivo comienza con las marcas de orden de bytes adecuadas.It automatically recognizes UTF-8, little-endian Unicode, big-endian Unicode, little-endian UTF-32, and big-endian UTF-32 text if the file starts with the appropriate byte order marks. De lo contrario, se utiliza la codificación proporcionada por el usuario.Otherwise, the user-provided encoding is used. Vea el método Encoding.GetPreamble para más información.See the Encoding.GetPreamble method for more information.

Nota

Al leer desde un Stream , es más eficaz utilizar un búfer que tenga el mismo tamaño que el búfer interno de la secuencia.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.

Precaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural determinada y se recuperan esos mismos caracteres con una configuración cultural diferente, es posible que los caracteres no se interpreten correctamente y que se produzca una excepción.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpreted correctly, and could cause an exception to be thrown.

Se aplica a