Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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

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

Show:
© 2016 Microsoft