How to: Write Text to a File

This topic shows different ways you can write text to a file for .NET Framework applications or Windows 8.x Store apps. The following classes and methods are typically used to write text to a file:

The samples have been kept simple in order to focus on the task being performed. For this reason, the samples perform minimal error checking and exception handling, if any. A real-world application generally provides more robust error checking and exception handling.

Example

The following example shows how to synchronously write text to a new file using the StreamWriter class, one line at a time. The new text file is saved to the user's My Documents folder. 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(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(mydocpath & Convert.ToString("\WriteLines.txt"))
    For Each line As String In lines
        outputFile.WriteLine(line)
    Next
End Using

Example

The following example shows how to append text to an existing file using the StreamWriter class. 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(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(mydocpath & Convert.ToString("\WriteLines.txt"), True)
    outputFile.WriteLine("Fourth Line")
End Using

Example

The following example shows how to asynchronously write text to a new file using the StreamWriter class. In order to invoke the WriteAsync method, the method call needs to be within an async method. 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(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(mydocpath & Convert.ToString("\WriteTextAsync.txt"))
        Await outputFile.WriteAsync(text)
    End Using
End Sub

Example

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. The WriteAllText and AppendAllLines methods open and close the file automatically. 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(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(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(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(mydocpath & Convert.ToString("\WriteFile.txt"), lines)

Example

The following example shows how to asynchronously write user input to a text file in a Windows 8.x Store app. Because of security considerations, opening a file from a Windows 8.x Store app typically requires the use of a FileOpenPicker control. 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

See Also

StreamWriter
System.IO.File.CreateText
How to: Enumerate Directories and Files
How to: Read and Write to a Newly Created Data File
How to: Open and Append to a Log File
How to: Read Text from a File
File and Stream I-O