File.WriteAllText 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.
Cria um novo ficheiro, escreve o conteúdo no ficheiro e depois fecha o ficheiro. Se o ficheiro de destino já existir, é truncado e sobrescrevido.
Sobrecargas
| Name | Description |
|---|---|
| WriteAllText(String, String) |
Cria um novo ficheiro, escreve a string especificada no ficheiro e depois fecha o ficheiro. Se o ficheiro de destino já existir, é truncado e sobrescrevido. |
| WriteAllText(String, String, Encoding) |
Cria um novo ficheiro, escreve a string especificada no ficheiro usando a codificação especificada e depois fecha o ficheiro. Se o ficheiro de destino já existir, é truncado e sobrescrevido. |
WriteAllText(String, String)
Cria um novo ficheiro, escreve a string especificada no ficheiro e depois fecha o ficheiro. Se o ficheiro de destino já existir, é truncado e sobrescrevido.
public:
static void WriteAllText(System::String ^ path, System::String ^ contents);
public static void WriteAllText(string path, string contents);
static member WriteAllText : string * string -> unit
Public Shared Sub WriteAllText (path As String, contents As String)
Parâmetros
- path
- String
O ficheiro para escrever.
- contents
- String
A cadeia a escrever no ficheiro.
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).
Ocorreu um erro de E/S durante a abertura do ficheiro.
path especificou um ficheiro que é apenas leitura.
-ou-
path especificou um ficheiro que está oculto.
-ou-
Esta operação não é suportada na plataforma atual.
-ou-
path especificava um diretório.
-ou-
O interlocutor não tem a permissão necessária.
path está num formato inválido.
O interlocutor não tem a permissão necessária.
Exemplos
O exemplo de código seguinte demonstra a utilização do WriteAllText método para escrever texto num ficheiro. Neste exemplo, um ficheiro é criado, se ainda não existir, e é adicionado texto a ele.
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
open System
open System.IO
let path = @"c:\temp\MyTest.txt"
// This text is added only once to the file.
if File.Exists path |> not then
// Create a file to write to.
let createText =
"Hello and Welcome" + Environment.NewLine
File.WriteAllText(path, createText)
// This text is always added, making the file longer over time
// if it is not deleted.
let appendText =
"This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
// Open the file to read from.
let readText = File.ReadAllText path
printfn $"{readText}"
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText As String = "Hello and Welcome" + Environment.NewLine
File.WriteAllText(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText As String = File.ReadAllText(path)
Console.WriteLine(readText)
End Sub
End Class
Observações
Este método utiliza codificação UTF-8 sem uma Byte-Order Mark (BOM), pelo que ao usar o GetPreamble método devolve-se um array de bytes vazio. Se for necessário incluir um identificador UTF-8, como uma marca de ordem de bytes, no início de um ficheiro, use o WriteAllText(String, String, Encoding) método overload com UTF8 codificação.
Dada uma string e um caminho de ficheiro, este método abre o ficheiro especificado, escreve a string no ficheiro e depois fecha o ficheiro.
Aplica-se a
WriteAllText(String, String, Encoding)
Cria um novo ficheiro, escreve a string especificada no ficheiro usando a codificação especificada e depois fecha o ficheiro. Se o ficheiro de destino já existir, é truncado e sobrescrevido.
public:
static void WriteAllText(System::String ^ path, System::String ^ contents, System::Text::Encoding ^ encoding);
public static void WriteAllText(string path, string contents, System.Text.Encoding encoding);
static member WriteAllText : string * string * System.Text.Encoding -> unit
Public Shared Sub WriteAllText (path As String, contents As String, encoding As Encoding)
Parâmetros
- path
- String
O ficheiro para escrever.
- contents
- String
A cadeia a escrever no ficheiro.
- encoding
- Encoding
A codificação a aplicar à string.
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).
Ocorreu um erro de E/S durante a abertura do ficheiro.
path especificou um ficheiro que é apenas leitura.
-ou-
path especificou um ficheiro que está oculto.
-ou-
Esta operação não é suportada na plataforma atual.
-ou-
path especificava um diretório.
-ou-
O interlocutor não tem a permissão necessária.
path está num formato inválido.
O interlocutor não tem a permissão necessária.
Exemplos
O exemplo de código seguinte demonstra a utilização do WriteAllText método para escrever texto num ficheiro. Neste exemplo, um ficheiro é criado, se ainda não existir, e é adicionado texto a ele.
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText, Encoding.UTF8);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText, Encoding.UTF8);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
open System
open System.IO
open System.Text
let path = @"c:\temp\MyTest.txt"
// This text is added only once to the file.
if File.Exists path |> not then
// Create a file to write to.
let createText =
"Hello and Welcome" + Environment.NewLine
File.WriteAllText(path, createText, Encoding.UTF8)
// This text is always added, making the file longer over time
// if it is not deleted.
let appendText =
"This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText, Encoding.UTF8)
// Open the file to read from.
let readText = File.ReadAllText path
printfn $"{readText}"
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText As String = "Hello and Welcome" + Environment.NewLine
File.WriteAllText(path, createText, Encoding.UTF8)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText, Encoding.UTF8)
' Open the file to read from.
Dim readText As String = File.ReadAllText(path)
Console.WriteLine(readText)
End Sub
End Class
Observações
Dada uma string e um caminho de ficheiro, este método abre o ficheiro especificado, escreve a string no ficheiro usando a codificação especificada e depois fecha o ficheiro. O handle do ficheiro é garantidamente fechado por este método, mesmo que sejam criadas exceções.