File.OpenRead(String) Método

Definição

Abre um ficheiro existente para leitura.

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

O ficheiro a ser aberto para leitura.

Devoluções

Um sistema de leitura FileStream somente no caminho especificado.

Exceções

.NET Framework e .NET Core versões anteriores à 2.1: path é uma cadeia de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Pode consultar caracteres inválidos usando o GetInvalidPathChars() método.

path é null.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado é inválido (por exemplo, está num disco não mapeado).

path especificava um diretório.

-ou-

O interlocutor não tem a permissão necessária.

O ficheiro especificado path não foi encontrado.

path está num formato inválido.

Ocorreu um erro de E/S durante a abertura do ficheiro.

Exemplos

O exemplo seguinte abre um ficheiro para leitura.

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));
            }
        }
    }
}
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 fs = File.OpenRead path
    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true

    while fs.Read(b, 0, b.Length) > 0 do
        printfn $"{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

Observações

Este método é equivalente à FileStream(String, FileMode, FileAccess, FileShare) sobrecarga de construtores com um FileMode valor de Open, um FileAccess valor de Read e um FileShare valor de Read.

O path parâmetro pode especificar informação relativa ou absoluta do caminho. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Para obter o diretório de trabalho atual, veja GetCurrentDirectory.

Para uma lista de tarefas comuns de E/S, consulte Tarefas Comuns de E/S.

Aplica-se a

Ver também