File.OpenText(String) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Abre um ficheiro de texto codificado em UTF-8 existente para leitura.
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
O ficheiro a ser aberto para leitura.
Devoluções
A StreamReader no caminho especificado.
Exceções
O interlocutor não tem a permissão necessária.
.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).
O ficheiro especificado path não foi encontrado.
path está num formato inválido.
Exemplos
O exemplo seguinte abre um ficheiro de texto 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 (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
Observações
Este método é equivalente à StreamReader(String) sobrecarga do construtor.
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.