Windows Dev Center

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

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.

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Set a variable to the My Documents path. 
        string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        StringBuilder sb = new StringBuilder();

        // Enumerate the files in the My Documents path, filtering for text files only. 
        foreach (string txtName 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 (StreamReader sr = new StreamReader(txtName))
            {
                sb.AppendLine(txtName);
                sb.AppendLine("= = = = = =");
                sb.Append(sr.ReadToEnd());
                sb.AppendLine();
                sb.AppendLine();
            }
        }
        // Write the stream contents to a new file named "AllTxtFiles.txt".
        using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
        {
            outfile.Write(sb.ToString());
        }
    }
}

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.

using System;
using System.Text;
using System.Windows;
using System.IO;

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void AppendButton_Click(object sender, RoutedEventArgs e)
        {
            // Set a variable to the My Documents path. 
            string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // Create a stringbuilder and write the new user input to it.
            StringBuilder sb = new StringBuilder();

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

            // Open a streamwriter to a new text file named "UserInputFile.txt"and write the contents of 
            // the stringbuilder to it. 
            using (StreamWriter outfile = new StreamWriter(mydocpath + @"\UserInputFile.txt", true))
            {
                await outfile.WriteAsync(sb.ToString());
            }
        }
    }
}

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

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

            // Create a string builder to hold the contents of the textbox.
            StringBuilder sb = new StringBuilder();

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

            if (result != null)
            {
                try
                {
                    // Use the WindowsRuntimeStorageExtension method to open  
                    // the stream for writing. 
                    var stream = await result.OpenStreamForWriteAsync();
                    using (StreamWriter sw = 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());
                    }
                }
                //Catching a generic exception 
                catch (IOException ex)
                {
                    UserInputTextBox.Text = "Error occurred reading the file. " + ex.Message;
                }
            }
            else
            {
                UserInputTextBox.Text = "User did not pick a file";
            }
        }
    }
}
Show:
© 2015 Microsoft