Cómo: Escribir texto en un archivoHow to: Write Text to a File

En este tema se describen diferentes formas de escribir texto en un archivo para aplicaciones de .NET Framework o aplicaciones de Tienda Windows 8.xWindows 8.x Store .This topic shows different ways you can write text to a file for .NET Framework applications or Tienda Windows 8.xWindows 8.x Store apps. Las clases y los métodos siguientes normalmente se usan para escribir texto en un archivo:The following classes and methods are typically used to write text to a file:

Presentamos ejemplos sencillos para permitirle centrarse en la tarea que esté realizando.The samples have been kept simple in order to focus on the task being performed. Por este motivo, en los ejemplos se realizan una comprobación de errores y un control de excepciones mínimos, si hubiera.For this reason, the samples perform minimal error checking and exception handling, if any. Generalmente, una aplicación real ofrece una comprobación de errores y un control de excepciones más exhaustivos.A real-world application generally provides more robust error checking and exception handling.

EjemploExample

En el ejemplo siguiente se muestra cómo escribir texto en un archivo nuevo de forma sincrónica mediante la clase StreamWriter , una línea a la vez.The following example shows how to synchronously write text to a new file using the StreamWriter class, one line at a time. El nuevo archivo de texto se guarda en la carpeta Mis documentos del usuario.The new text file is saved to the user's My Documents folder. Dado que en la instrucción StreamWriter se declara el objeto using y se crea una instancia de este, se invoca el método Dispose que automáticamente vacía y cierra el flujo.Because the StreamWriter object is declared and instantiated in a using statement, the Dispose method is invoked which automatically flushes and closes the stream.

// Create a string array with the lines of text
string[] lines = { "First line", "Second line", "Third line" };

// Set a variable to the My Documents path.
string mydocpath =
    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Write the string array to a new file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath,"WriteLines.txt"))) {
    foreach (string line in lines)
        outputFile.WriteLine(line);
}
' Create a string array with the lines of text
Dim lines() As String = {"First line", "Second line", "Third line"}

' Set a variable to the My Documents path.
Dim mydocpath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

' Write the string array to a new file named "WriteLines.txt".
Using outputFile As New StreamWriter(Path.Combine(mydocpath,Convert.ToString("WriteLines.txt")))
    For Each line As String In lines
        outputFile.WriteLine(line)
    Next
End Using

EjemploExample

En el ejemplo siguiente se muestra cómo anexar texto a un archivo existente mediante la clase StreamWriter .The following example shows how to append text to an existing file using the StreamWriter class. Se usa el mismo archivo de texto del ejemplo anterior.It uses the same text file from the previous example.

// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Append text to an existing file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath,"WriteLines.txt"), true)) {
    outputFile.WriteLine("Fourth Line");
}
        ' Set a variable to the My Documents path.
        Dim mydocpath As String =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Append text to an existing file named "WriteLines.txt".
Using outputFile As New StreamWriter(Path.Combine(mydocpath,Convert.ToString("WriteLines.txt")), True)
            outputFile.WriteLine("Fourth Line")
        End Using

EjemploExample

En el ejemplo siguiente se muestra cómo escribir texto en un archivo nuevo de forma asincrónica mediante la clase StreamWriter .The following example shows how to asynchronously write text to a new file using the StreamWriter class. Para invocar el método WriteAsync , la llamada al método debe estar dentro de un método async .In order to invoke the WriteAsync method, the method call needs to be within an async method. El nuevo archivo de texto se guarda en la carpeta Mis documentos del usuario.The new text file is saved to the user's My Documents folder.

static async void WriteTextAsync(string text)
{
    // Set a variable to the My Documents path.
    string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    // Write the text asynchronously to a new file named "WriteTextAsync.txt".
    using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath,"WriteTextAsync.txt"))) {
        await outputFile.WriteAsync(text);
    }
}
    Shared Async Sub WriteTextAsync(text As String)
        ' Set a variable to the My Documents path.
        Dim mydocpath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Write the text asynchronously to a new file named "WriteTextAsync.txt".
Using outputFile As New StreamWriter(Path.Combine(mydocpath,Convert.ToString("WriteTextAsync.txt")))
            Await outputFile.WriteAsync(text)
        End Using
    End Sub

EjemploExample

En el ejemplo siguiente se muestra cómo escribir texto en un archivo nuevo y anexar nuevas líneas de texto en el mismo archivo con la clase File .The following example shows how to write text to a new file and append new lines of text to the same file using the File class. Los métodos WriteAllText y AppendAllLines abren y cierran el archivo automáticamente.The WriteAllText and AppendAllLines methods open and close the file automatically. Si ya existe la ruta de acceso al método WriteAllText proporcionada, se sobrescribe el archivo.If the path you provide to the WriteAllText method already exists, the file will be overwritten.

// Create a string array with the lines of text
string text = "First line" + Environment.NewLine;

// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(mydocpath,"WriteFile.txt"), text);

// Create a string array with the additional lines of text
string[] lines = { "New line 1", "New line 2" };

// Append new lines of text to the file
File.AppendAllLines(Path.Combine(mydocpath,"WriteFile.txt"), lines);
        ' Create a string array with the lines of text
        Dim text As String = "First line" & Environment.NewLine

        ' Set a variable to the My Documents path.
        Dim mydocpath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(mydocpath,Convert.ToString("WriteFile.txt")), text)

        ' Create a string array with the additional lines of text
        Dim lines() As String = {"New line 1", "New line 2"}

        ' Append new lines of text to the file
File.AppendAllLines(Path.Combine(mydocpath,Convert.ToString("WriteFile.txt")), lines)

EjemploExample

En el siguiente ejemplo se muestra cómo escribir asincrónicamente en un archivo de texto los datos proporcionados por el usuario en una aplicación de la Tienda Windows 8.xWindows 8.x Store .The following example shows how to asynchronously write user input to a text file in a Tienda Windows 8.xWindows 8.x Store app. Por cuestiones de seguridad, la apertura de un archivo desde una aplicación de Tienda Windows 8.xWindows 8.x Store normalmente requiere el uso de un control FileOpenPicker .Because of security considerations, opening a file from a Tienda Windows 8.xWindows 8.x Store app typically requires the use of a FileOpenPicker control. En este ejemplo, FileOpenPicker se filtra para mostrar archivos de texto.In this example, the FileOpenPicker is filtered to show text files.

<Page  
    x:Class="OpenFileWindowsStore.MainPage"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:local="using:OpenFileWindowsStore"  
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    mc:Ignorable="d">  

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
        <Button Content="save text to a file" HorizontalAlignment="Left" Margin="103,417,0,0" VerticalAlignment="Top"   
                Width="329" Height="86" FontSize="35" Click="Button_Click"/>  
        <TextBox Name="UserInputTextBox"  FontSize="18" HorizontalAlignment="Left" Margin="106,146,0,0"   
                 TextWrapping="Wrap" Text="Write some text here, and select a file to write it to." VerticalAlignment="Top"   
                 Height="201" Width="558" AcceptsReturn="True"/>  
        <TextBlock Name="StatusTextBox" HorizontalAlignment="Left" Margin="106,570,0,147" TextWrapping="Wrap" Text="Status:"   
                   VerticalAlignment="Center" Height="51" Width="1074" FontSize="18" />  
    </Grid>  
</Page>  
using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Storage;
using System.Text;
using Windows.Storage.Pickers;
using Windows.UI.Popups; 

namespace OpenFileWindowsStore
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        // Create a file picker to open a file. Most file access in Windows Store Apps
        // requires the use of a file picker for security purposes.
        FileOpenPicker picker = new FileOpenPicker();
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
         
           // Set properties on the file picker such as start location and the type 
            // of files to display.
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.ViewMode = PickerViewMode.List;
            picker.FileTypeFilter.Add(".txt");

            // Show picker enabling user to pick one file.
            StorageFile result = await picker.PickSingleFileAsync();

            if (result != null)
            {
                try
                {
                    // Use FileIO to replace the content of the text file
                    await FileIO.WriteTextAsync(result, UserInputTextBox.Text);

                    // Display a success message
                    StatusTextBox.Text = "Status: File saved successfully";
                }
                catch (Exception ex)
                {
                    // Display an error message
                    StatusTextBox.Text = "Status: error saving the file - " + ex.Message;
                }
            }
            else
                StatusTextBox.Text = "Status: User cancelled save operation";
        }
    }
}
Imports System.IO
Imports System.Runtime.InteropServices.WindowsRuntime
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.Storage
Imports System.Text
Imports Windows.Storage.Pickers
Imports Windows.UI.Popups
Partial Public NotInheritable Class MainPage
    Inherits Page
    Public Sub New()
        Me.InitializeComponent()
    End Sub

    ' Create a file picker to open a file. Most file access in Windows Store Apps
    ' requires the use of a file picker for security purposes.
    Private picker As New FileOpenPicker()
    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)

        ' Set properties on the file picker such as start location and the type 
        ' of files to display.
        picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
        picker.ViewMode = PickerViewMode.List
        picker.FileTypeFilter.Add(".txt")

        ' Show picker enabling user to pick one file.
        Dim result As StorageFile = Await picker.PickSingleFileAsync()

        If result IsNot Nothing Then
            Try
                ' Use FileIO to replace the content of the text file
                Await FileIO.WriteTextAsync(result, UserInputTextBox.Text)

                ' Display a success message
                StatusTextBox.Text = "Status: File saved successfully"
            Catch ex As Exception
                ' Display an error message
                StatusTextBox.Text = "Status: error saving the file - " + ex.Message
            End Try
        Else
            StatusTextBox.Text = "Status: User cancelled save operation"
        End If
    End Sub
End Class

Vea tambiénSee Also

StreamWriter
Path
File.CreateText
Enumerar directorios y archivosHow to: Enumerate Directories and Files
Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File
Cómo: Abrir y anexar a un archivo de registroHow to: Open and Append to a Log File
Cómo: Leer texto de un archivoHow to: Read Text from a File
E/S de archivos y secuenciasFile and Stream I/O