Compartilhar via


Como: Gravar um arquivo de texto

O exemplo de código a seguir demonstra como criar um arquivo de texto e escrever o texto para ele usando o StreamWriter classe, que é definido na System.IO namespace. The StreamWriter construtor obtém o nome do arquivo a ser criado. Se o arquivo existir, ele será sobrescrito (a menos que você passar true sistema autônomo o segundo StringWriter argumento do construtor).

O arquivo é arquivado, em seguida, usando o Write e WriteLine funções.

Exemplo

// text_write.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main() 
{
   String^ fileName = "textfile.txt";

   StreamWriter^ sw = gcnew StreamWriter(fileName);
   sw->WriteLine("A text file is born!");
   sw->Write("You can use WriteLine");
   sw->WriteLine("...or just Write");
   sw->WriteLine("and do {0} output too.", "formatted");
   sw->WriteLine("You can also send non-text objects:");
   sw->WriteLine(DateTime::Now);
   sw->Close();
   Console::WriteLine("a new file ('{0}') has been written", fileName);

   return 0;
}

Consulte também

Outros recursos

E/S de arquivo e de fluxo

Guia de programação .NET