File.WriteAllText Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Cria um novo arquivo, grava os conteúdos nele e o fecha. Se o arquivo de destino já existir, ele será truncado e substituído.
Sobrecargas
WriteAllText(String, String) |
Cria um novo arquivo, grava a cadeia de caracteres especificada no arquivo e fecha o arquivo. Se o arquivo de destino já existir, ele será truncado e substituído. |
WriteAllText(String, String, Encoding) |
Cria um novo arquivo, grava a cadeia de caracteres especificada no arquivo usando a codificação especificada e fecha o arquivo. Se o arquivo de destino já existir, ele será truncado e substituído. |
WriteAllText(String, String)
- Origem:
- File.cs
- Origem:
- File.cs
- Origem:
- File.cs
Cria um novo arquivo, grava a cadeia de caracteres especificada no arquivo e fecha o arquivo. Se o arquivo de destino já existir, ele será truncado e substituído.
public:
static void WriteAllText(System::String ^ path, System::String ^ contents);
public static void WriteAllText (string path, 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 arquivo para gravação.
- contents
- String
A cadeia de caracteres a ser gravada no arquivo.
Exceções
.NET Framework e versões do .NET Core anteriores à 2.1: path
é uma cadeia de caracteres de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Consulte caracteres inválidos usando o método GetInvalidPathChars().
path
é null
.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).
Um erro de E/S ocorreu ao abrir o arquivo.
path
especificou um arquivo somente leitura.
- ou -
path
especificou um arquivo que está oculto.
- ou -
Não há suporte para essa operação na plataforma atual.
- ou -
path
especificou um diretório.
- ou -
O chamador não tem a permissão necessária.
path
está em um formato inválido.
O chamador não tem a permissão necessária.
Exemplos
O exemplo de código a seguir demonstra o uso do WriteAllText método para gravar texto em um arquivo. Neste exemplo, um arquivo será criado, se ele ainda não existir, e o texto será adicionado 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
Comentários
Esse método usa a codificação UTF-8 sem uma BOM (marca de Byte-Order), portanto, o uso do GetPreamble método retornará uma matriz de bytes vazia. Se for necessário incluir um identificador UTF-8, como uma marca de ordem de byte, no início de um arquivo, use a sobrecarga de WriteAllText(String, String, Encoding) método com UTF8 codificação.
Dada uma cadeia de caracteres e um caminho de arquivo, esse método abre o arquivo especificado, grava a cadeia de caracteres no arquivo e fecha o arquivo.
Aplica-se a
WriteAllText(String, String, Encoding)
- Origem:
- File.cs
- Origem:
- File.cs
- Origem:
- File.cs
Cria um novo arquivo, grava a cadeia de caracteres especificada no arquivo usando a codificação especificada e fecha o arquivo. Se o arquivo de destino já existir, ele será truncado e substituído.
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);
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 arquivo para gravação.
- contents
- String
A cadeia de caracteres a ser gravada no arquivo.
- encoding
- Encoding
A codificação a ser aplicada à cadeia de caracteres.
Exceções
.NET Framework e versões do .NET Core anteriores à 2.1: path
é uma cadeia de caracteres de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Consulte caracteres inválidos usando o método GetInvalidPathChars().
path
é null
.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).
Um erro de E/S ocorreu ao abrir o arquivo.
path
especificou um arquivo somente leitura.
- ou -
path
especificou um arquivo que está oculto.
- ou -
Não há suporte para essa operação na plataforma atual.
- ou -
path
especificou um diretório.
- ou -
O chamador não tem a permissão necessária.
path
está em um formato inválido.
O chamador não tem a permissão necessária.
Exemplos
O exemplo de código a seguir demonstra o uso do WriteAllText método para gravar texto em um arquivo. Neste exemplo, um arquivo será criado, se ele ainda não existir, e o texto será adicionado 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
Comentários
Dada uma cadeia de caracteres e um caminho de arquivo, esse método abre o arquivo especificado, grava a cadeia de caracteres no arquivo usando a codificação especificada e fecha o arquivo. O identificador de arquivo tem a garantia de ser fechado por esse método, mesmo que exceções sejam geradas.
Aplica-se a
Comentários
https://aka.ms/ContentUserFeedback.
Brevemente: Ao longo de 2024, vamos descontinuar progressivamente o GitHub Issues como mecanismo de feedback para conteúdos e substituí-lo por um novo sistema de feedback. Para obter mais informações, veja:Submeter e ver comentários