Export (0) Print
Expand All

How to: Write Text to a File

The following examples show how to write to a text file from a console app, a Windows Presentation Foundation (WPF) app and a Windows Store app.

This example reads all the text files from the user's My Documents folder by searching for "*.txt", and synchronously writes them into a large text file.

Imports System
Imports System.IO
Imports System.Text
Imports System.Collections.Generic

Class Program

    Public Shared Sub Main(ByVal args As String())
        ' Set a variable to the My Documents path. 
        Dim mydocpath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim sb As New StringBuilder()
        ' Enumerate the files in teh My Documents path, filtering for text files only. 
        For Each txtName As String In Directory.EnumerateFiles(mydocpath, "*.txt")
            ' Open a stream reader and write the name of the file, a visual separator, and the contents 
            ' of the file to the stream. 
            Using sr As New StreamReader(txtName)
                sb.AppendLine(txtName.ToString())
                sb.AppendLine("= = = = = =")
                sb.Append(sr.ReadToEnd())
                sb.AppendLine()
                sb.AppendLine()
            End Using 
        Next 
        ' Write the stream cotnents to a new file named "AllTxtFiles.txt" 
        Using outfile As New StreamWriter(mydocpath & "\AllTxtFiles.txt")
            outfile.Write(sb.ToString())
        End Using 
    End Sub 
End Class

This example shows how to asynchronously write user input from a text box in a Windows Presentation Foundation (WPF) app to a file. In order to run this example, you must create a WPF app that contains a text box named UserInputTextBox.

Imports System.IO
Imports System.Text

Class MainWindow

    Private Async Sub AppendButton_Click(sender As Object, e As RoutedEventArgs)
        ' Set a variable to the My Documents path. 
        Dim mydocpath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Create a string builder and write the user input from the textbox to it. 
        Dim sb As StringBuilder = New StringBuilder()
        sb.AppendLine("New User Input")
        sb.AppendLine("= = = = = =")
        sb.Append(UserInputTextBox.Text)
        sb.AppendLine()
        sb.AppendLine()

        ' Open a stream writer to a new text file named "UserInputFile.txt" and write the contents  
        ' of the stringbuilder to it. 
        Using outfile As StreamWriter = New StreamWriter(mydocpath + "\UserInputFile.txt", True)
            Await outfile.WriteAsync(sb.ToString())
        End Using 
    End Sub 
End Class

The following example shows how to asynchronously write user input to a text file in a Windows Store app. Because of security considerations, opening a file from a Windows 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="pick file" HorizontalAlignment="Left" Margin="778,216,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"/>
     </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

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

        ' Create a string builder to hold the contents of the textbox. 
        Dim sb As New StringBuilder()

        sb.AppendLine("New User Input")
        sb.AppendLine("= = = = = =")
        sb.Append(UserInputTextBox.Text)
        sb.AppendLine()
        sb.AppendLine()

        If result IsNot Nothing Then 
            Try 
                ' Use the WindowsRuntimeStorageExtension method to open  
                ' the stream for writing. 
                Dim stream = Await result.OpenStreamForWriteAsync()
                Using sw As New StreamWriter(stream)
                    ' Write the contents of the string buffer to the stream. 
                    ' This will overwrite the contents at the beginning of the file.
                    Await sw.WriteLineAsync(sb.ToString())
                End Using 
                'Catching a generic exception 
            Catch ex As IOException
                UserInputTextBox.Text = "Error occurred reading the file. " & ex.Message
            End Try 
        Else
            UserInputTextBox.Text = "User did not pick a file" 
        End If 
    End Sub 
End Class
Show:
© 2014 Microsoft