File.OpenRead(String) Método

Definición

Abre un archivo existente para lectura.

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

Parámetros

path
String

Archivo que se va a abrir para la lectura.

Devoluciones

FileStream

FileStream de solo lectura en la ruta de acceso especificada.

Excepciones

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

path especificó un directorio.

o bien El llamador no dispone del permiso requerido.

No se encontró el archivo especificado en path.

path está en un formato no válido.

Se produjo un error de E/S al abrir el archivo.

Ejemplos

En el ejemplo siguiente se abre un archivo para leer.

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.
   FileStream^ fs = File::OpenRead( path );
   try
   {
      array<Byte>^b = gcnew array<Byte>(1024);
      UTF8Encoding^ temp = gcnew UTF8Encoding( true );
      while ( fs->Read( b, 0, b->Length ) > 0 )
      {
         Console::WriteLine( temp->GetString( b ) );
      }
   }
   finally
   {
      if ( fs )
         delete (IDisposable^)fs;
   }
}
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 (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
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 fs As FileStream = File.OpenRead(path)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)

      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop
    End Using

  End Sub
End Class

Comentarios

Este método es equivalente a la FileStream(String, FileMode, FileAccess, FileShare) sobrecarga del constructor con un FileMode valor de Open, un FileAccess valor de Read y un FileShare valor de Read.

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