FileSystem.WriteAllText Método
Definição
Grava um texto em um arquivo.Writes text to a file.
Sobrecargas
| WriteAllText(String, String, Boolean) |
Grava um texto em um arquivo.Writes text to a file. |
| WriteAllText(String, String, Boolean, Encoding) |
Grava um texto em um arquivo.Writes text to a file. |
WriteAllText(String, String, Boolean)
Grava um texto em um arquivo.Writes text to a file.
public:
static void WriteAllText(System::String ^ file, System::String ^ text, bool append);
public static void WriteAllText (string file, string text, bool append);
static member WriteAllText : string * string * bool -> unit
Public Shared Sub WriteAllText (file As String, text As String, append As Boolean)
Parâmetros
- file
- String
Arquivos que serão gravados.File to be written to.
- text
- String
O texto a ser gravado no arquivo.Text to be written to file.
- append
- Boolean
True para acrescentar ao conteúdo do arquivo; False para substituir o conteúdo do arquivo.True to append to the contents of the file; False to overwrite the contents of the file.
Exceções
O caminho não é válido por um dos seguintes motivos: é uma cadeia de tamanho zero, contém apenas espaços em branco, contém caracteres inválidos ou é um caminho de dispositivo (começa com \\.\); ele termina com uma barra à direita.The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains invalid characters; or it is a device path (starts with \\.\); it ends with a trailing slash.
file é Nothing.file is Nothing.
O arquivo não existe.The file does not exist.
O arquivo está sendo usado por outro processo, ou ocorre um erro de E/S.The file is in use by another process, or an I/O error occurs.
O caminho excede o tamanho máximo definido pelo sistema.The path exceeds the system-defined maximum length.
Um nome de arquivo ou de diretório no caminho contém dois-pontos (:) ou está em um formato inválido.A file or directory name in the path contains a colon (:) or is in an invalid format.
Não há memória suficiente para gravar a cadeia de caracteres no buffer.There is not enough memory to write the string to buffer.
O usuário não tem as permissões necessárias para exibir o caminho.The user lacks necessary permissions to view the path.
Exemplos
Este exemplo grava a linha no "This is new text to be added." arquivo Test.txt , substituindo qualquer texto existente no arquivo.This example writes the line "This is new text to be added." to the file Test.txt, overwriting any existing text in the file.
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt",
"This is new text to be added.", False)
Este exemplo grava os nomes dos arquivos na Documents and Settings pasta para FileList.txt , inserindo um retorno de carro entre cada para melhor legibilidade.This example writes the names of the files in the Documents and Settings folder to FileList.txt, inserting a carriage return between each for better readability.
For Each foundFile In
My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText(
"C:\Documents and Settings\FileList.txt", foundFile, True)
Next
Comentários
A codificação UTF-8 é usada para gravar no arquivo.The UTF-8 encoding is used to write to the file. Para especificar uma codificação diferente, use uma sobrecarga diferente do WriteAllText método.To specify a different encoding, use a different overload of the WriteAllText method.
Se o arquivo especificado não existir, ele será criado.If the specified file does not exist, it is created.
Se a codificação especificada não corresponder à codificação existente do arquivo, a codificação especificada será ignorada.If the specified encoding does not match the existing encoding of the file, the specified coding is ignored.
Observação
O WriteAllText método abre um arquivo, grava nele e o fecha.The WriteAllText method opens a file, writes to it, and then closes it. O código que usa o WriteAllText método é mais simples do que o código que usa um StreamWriter objeto.Code that uses the WriteAllText method is simpler than code that uses a StreamWriter object. No entanto, se você estiver adicionando cadeias de caracteres a um arquivo usando um loop, um StreamWriter objeto poderá fornecer melhor desempenho porque você só precisa abrir e fechar o arquivo uma vez.However, if you are adding strings to a file by using a loop, a StreamWriter object can provide better performance because you only have to open and close the file one time. Para obter mais informações, consulte o método OpenTextFileWriter.For more information, see the OpenTextFileWriter method.
A tabela a seguir lista exemplos de tarefas que envolvem o My.Computer.FileSystem.WriteAllText método.The following table lists examples of tasks involving the My.Computer.FileSystem.WriteAllText method.
| ParaTo | ConsulteSee |
|---|---|
| Gravar texto em um arquivoWrite text to a file | Como gravar texto em arquivos no Visual BasicHow to: Write Text to Files in Visual Basic |
| Anexar texto em um arquivoAppend text to a file | Como anexar a arquivos de texto no Visual BasicHow to: Append to Text Files in Visual Basic |
Confira também
Aplica-se a
WriteAllText(String, String, Boolean, Encoding)
Grava um texto em um arquivo.Writes text to a file.
public:
static void WriteAllText(System::String ^ file, System::String ^ text, bool append, System::Text::Encoding ^ encoding);
public static void WriteAllText (string file, string text, bool append, System.Text.Encoding encoding);
static member WriteAllText : string * string * bool * System.Text.Encoding -> unit
Public Shared Sub WriteAllText (file As String, text As String, append As Boolean, encoding As Encoding)
Parâmetros
- file
- String
Arquivos que serão gravados.File to be written to.
- text
- String
O texto a ser gravado no arquivo.Text to be written to file.
- append
- Boolean
True para acrescentar ao conteúdo do arquivo; False para substituir o conteúdo do arquivo.True to append to the contents of the file; False to overwrite the contents of the file.
- encoding
- Encoding
A codificação a ser utilizada ao gravar um arquivo.What encoding to use when writing to file.
Exceções
O caminho não é válido por um dos seguintes motivos: é uma cadeia de tamanho zero, contém apenas espaços em branco, contém caracteres inválidos ou é um caminho de dispositivo (começa com \\.\); ele termina com uma barra à direita.The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains invalid characters; or it is a device path (starts with \\.\); it ends with a trailing slash.
file é Nothing.file is Nothing.
O arquivo não existe.The file does not exist.
O arquivo está sendo usado por outro processo, ou ocorre um erro de E/S.The file is in use by another process, or an I/O error occurs.
O caminho excede o tamanho máximo definido pelo sistema.The path exceeds the system-defined maximum length.
Um nome de arquivo ou de diretório no caminho contém dois-pontos (:) ou está em um formato inválido.A file or directory name in the path contains a colon (:) or is in an invalid format.
Não há memória suficiente para gravar a cadeia de caracteres no buffer.There is not enough memory to write the string to buffer.
O usuário não tem as permissões necessárias para exibir o caminho.The user lacks necessary permissions to view the path.
Exemplos
Este exemplo grava a linha no "This is new text to be added." arquivo Test.txt , substituindo qualquer texto existente no arquivo.This example writes the line "This is new text to be added." to the file Test.txt, overwriting any existing text in the file.
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt",
"This is new text to be added.", False)
Este exemplo grava os nomes dos arquivos na Documents and Settings pasta para FileList.txt , inserindo um retorno de carro entre cada para melhor legibilidade.This example writes the names of the files in the Documents and Settings folder to FileList.txt, inserting a carriage return between each for better readability.
For Each foundFile In
My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText(
"C:\Documents and Settings\FileList.txt", foundFile, True)
Next
Comentários
Se o arquivo especificado não existir, ele será criado.If the specified file does not exist, it is created.
Se a codificação especificada não corresponder à codificação existente do arquivo, a codificação especificada será ignorada.If the specified encoding does not match the existing encoding of the file, the specified coding is ignored.
Observação
O WriteAllText método abre um arquivo, grava nele e o fecha.The WriteAllText method opens a file, writes to it, and then closes it. O código que usa o WriteAllText método é mais simples do que o código que usa um StreamWriter objeto.Code that uses the WriteAllText method is simpler than code that uses a StreamWriter object. No entanto, se você estiver adicionando cadeias de caracteres a um arquivo usando um loop, um StreamWriter objeto poderá fornecer melhor desempenho porque você só precisa abrir e fechar o arquivo uma vez.However, if you are adding strings to a file by using a loop, a StreamWriter object can provide better performance because you only have to open and close the file one time. Para obter mais informações, consulte o método OpenTextFileWriter.For more information, see the OpenTextFileWriter method.
A tabela a seguir lista exemplos de tarefas que envolvem o My.Computer.FileSystem.WriteAllText método.The following table lists examples of tasks involving the My.Computer.FileSystem.WriteAllText method.
| ParaTo | ConsulteSee |
|---|---|
| Gravar texto em um arquivoWrite text to a file | Como gravar texto em arquivos no Visual BasicHow to: Write Text to Files in Visual Basic |
| Anexar texto em um arquivoAppend text to a file | Como anexar a arquivos de texto no Visual BasicHow to: Append to Text Files in Visual Basic |