¿Le resultó útil esta página?
Sus comentarios sobre este contenido son muy importantes. Háganos saber su opinión.
¿Tiene comentarios adicionales?
Caracteres restantes: 1500
Exportar (0) Imprimir
Expandir todo
Este contenido no se encuentra disponible en su idioma, pero aquí tiene la versión en inglés.

How to: Write Text to a File 

The following code examples show how to write text to a text file.

The first example shows how to add text to an existing file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAllText methods.


Visual Basic users may choose to use the methods and properties provided by the My.Computer.FileSystem object for file I/O. For more information, see My.Computer.FileSystem Object.


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.");
            // Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
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);
        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);

See Also

Adiciones de comunidad

© 2015 Microsoft