Compartilhar via


Como: Gravar um arquivo de texto

Os seguintes exemplos de códigos mostram como escrever texto em um arquivo de texto.

O primeiro exemplo mostra como adicionar texto a um arquivo existente.O segundo exemplo mostra como criar um novo arquivo de texto e gravar uma sequência de caracteres nele.Funcionalidade semelhante pode ser fornecida pelos métodos WriteAllText.

Observação:

Os usuários do Visual Basic podem optar por usar os métodos e propriedades fornecidas pela My.Computer.FileSystem objeto para E/s de arquivo. Para obter mais informações, consulte Objeto My.Computer.FileSystem.

Exemplo

Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        ' Create an instance of StreamWriter to write text to a file.
        Using sw As StreamWriter = New StreamWriter("TestFile.txt")
            ' Add some text to the file.
            sw.Write("This is the ")
            sw.WriteLine("header for the file.")
            sw.WriteLine("-------------------")
            ' Arbitrary objects can also be written to the file.
            sw.Write("The date is: ")
            sw.WriteLine(DateTime.Now)
            sw.Close()
        End Using
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        // Create an instance of StreamWriter to write text to a file.
        // The using statement also closes the StreamWriter.
        using (StreamWriter sw = new StreamWriter("TestFile.txt")) 
        {
            // Add some text to the file.
            sw.Write("This is the ");
            sw.WriteLine("header for the file.");
            sw.WriteLine("-------------------");
            // Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
            sw.WriteLine(DateTime.Now);
        }
    }
}
Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class TextToFile
    Private Const FILE_NAME As String = "MyFile.txt"
    Public Shared Sub Main()
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists.", FILE_NAME)
            Return
        End If
        Using sw As StreamWriter = File.CreateText(FILE_NAME)
            sw.WriteLine("This is my file.")
            sw.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
            sw.Close()
        End Using
    End Sub
End Class
using System;
using System.IO;
public class TextToFile 
{
    private const string FILE_NAME = "MyFile.txt";
    public static void Main(String[] args) 
    {
        if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} already exists.", FILE_NAME);
            return;
        }
        using (StreamWriter sw = File.CreateText(FILE_NAME))
        {
            sw.WriteLine ("This is my file.");
            sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 
                1, 4.2);
            sw.Close();
        }
    }
}

Consulte também

Tarefas

Como: Criar uma listagem de diretório

Como: Ler e gravar em um arquivo de dados recém-criado

Como: em em aberto e anexar em um arquivo de log

Como: Ler texto de um arquivo

Como: Caracteres de leitura de uma seqüência de caracteres

Como: Escrever caracteres para uma string

Conceitos

Arquivo básico de E/S

Referência

StreamWriter

File.CreateText