File.CreateText(String) Método

Definição

Cria ou abre um arquivo para gravar texto codificado em UTF-8. Se o arquivo já existir, seu conteúdo será substituído.

public:
 static System::IO::StreamWriter ^ CreateText(System::String ^ path);
public static System.IO.StreamWriter CreateText (string path);
static member CreateText : string -> System.IO.StreamWriter
Public Shared Function CreateText (path As String) As StreamWriter

Parâmetros

path
String

O arquivo a ser aberto para gravação.

Retornos

Um StreamWriter que grava no arquivo especificado usando a codificação UTF-8.

Exceções

O chamador não tem a permissão necessária.

- ou -

path especificou um arquivo somente leitura.

- ou -

path especificou um arquivo que está oculto.

.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).

path está em um formato inválido.

Exemplos

O exemplo a seguir cria um arquivo para gravação e leitura de texto.

using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   if ( !File::Exists( path ) )
   {
      
      // Create a file to write to.
      StreamWriter^ sw = File::CreateText( path );
      try
      {
         sw->WriteLine( "Hello" );
         sw->WriteLine( "And" );
         sw->WriteLine( "Welcome" );
      }
      finally
      {
         if ( sw )
                  delete (IDisposable^)sw;
      }
   }
   
   // Open the file to read from.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
            delete (IDisposable^)sr;
   }
}
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }	
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
open System.IO

let path = @"c:\temp\MyTest.txt"

if File.Exists path |> not then
    // Create a file to write to.
    use sw = File.CreateText path
    sw.WriteLine "Hello"
    sw.WriteLine "Welcome"

// Open the file to read from.
do
    use sr = File.OpenText path
    let mutable s = sr.ReadLine()

    while isNull s |> not do
        printfn $"{s}"
        s <- sr.ReadLine()
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt"

    If Not File.Exists(path) Then
      ' Create a file to write to. 
      Using sw As StreamWriter = File.CreateText(path)
        sw.WriteLine("Hello")
        sw.WriteLine("And")
        sw.WriteLine("Welcome")
      End Using
    End If

    ' Open the file to read from. 
    Using sr As StreamReader = File.OpenText(path)
      Do While sr.Peek() >= 0
        Console.WriteLine(sr.ReadLine())
      Loop
    End Using

  End Sub
End Class

Comentários

Esse método é equivalente à sobrecarga do StreamWriter(String, Boolean) construtor com o append parâmetro definido falsecomo . Se o arquivo especificado por path não existir, ele será criado. Se o arquivo existir, seu conteúdo será substituído. Threads adicionais têm permissão para ler o arquivo enquanto ele está aberto.

O path parâmetro tem permissão para especificar informações de caminho relativas ou absolutas. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Aplica-se a

Confira também