File.OpenText(String) Método

Definición

Abre un archivo de texto existente con codificación UTF-8 para lectura.

public:
 static System::IO::StreamReader ^ OpenText(System::String ^ path);
public static System.IO.StreamReader OpenText (string path);
static member OpenText : string -> System.IO.StreamReader
Public Shared Function OpenText (path As String) As StreamReader

Parámetros

path
String

Archivo que se va a abrir para la lectura.

Devoluciones

StreamReader en la ruta de acceso especificada.

Excepciones

El llamador no dispone del permiso requerido.

Versiones de .NET Framework y .NET Core anteriores a 2.1: path es una cadena de longitud cero, solo contiene espacios en blanco o contiene uno o varios caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

path es null.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada no es válida (por ejemplo, está en una unidad no asignada).

No se encontró el archivo especificado en path.

path está en un formato no válido.

Ejemplos

En el ejemplo siguiente se abre un archivo de texto para su lectura.

using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   if ( !File::Exists( path ) )
   {
      // Create the file.
      FileStream^ fs = File::Create( path );
      try
      {
         array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." );
         
         // Add some information to the file.
         fs->Write( info, 0, info->Length );
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
   
   // Open the stream and read it back.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
         delete (IDisposable^)sr;
   }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        if (!File.Exists(path))
        {
            // Create the file.
            using (FileStream fs = File.Create(path))
            {
                Byte[] info =
                    new UTF8Encoding(true).GetBytes("This is some text in the file.");

                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        // Open the stream and read it back.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
open System.IO
open System.Text

let path = @"c:\temp\MyTest.txt"

if File.Exists path |> not then
    // Create the file.
    use fs = File.Create path

    let info =
        UTF8Encoding(true)
            .GetBytes "This is some text in the file."

    // Add some information to the file.
    fs.Write(info, 0, info.Length)

// Open the stream and read it back.
do
    use sr = File.OpenText path
    let mutable s = sr.ReadLine()

    while isNull s |> not do
        printfn $"{s}"
        s <- sr.ReadLine()
Imports System.IO
Imports System.Text

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

    If Not File.Exists(path) Then
      ' Create the file.
      Using fs As FileStream = File.Create(path)
        Dim info As Byte() = _
         New UTF8Encoding(True).GetBytes("This is some text in the file.")

        ' Add some information to the file.
        fs.Write(info, 0, info.Length)
      End Using
    End If

    ' Open the stream and read it back. 
    Using sr As StreamReader = File.OpenText(path)
      Do While sr.Peek() >= 0
        Console.WriteLine(sr.ReadLine())
      Loop
    End Using

  End Sub
End Class

Comentarios

Este método es equivalente a la sobrecarga del StreamReader(String) constructor.

El path parámetro puede especificar información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, vea GetCurrentDirectory.

Para obtener una lista de tareas de E/S comunes, consulte Tareas de E/S comunes.

Se aplica a

Consulte también