13 out of 32 rated this helpful - Rate this topic

How to: Write Text to a File

The following examples show how to write text to a text file.

The first 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)
    {
        string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        StringBuilder sb = new StringBuilder();

        foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt"))
        {
            using (StreamReader sr = new StreamReader(txtName))
            {
                sb.AppendLine(txtName.ToString());
                sb.AppendLine("= = = = = =");
                sb.Append(sr.ReadToEnd());
                sb.AppendLine();
                sb.AppendLine();
            }
        }

        using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
        {
            outfile.Write(sb.ToString());
        }
    }
}

The next example shows how to asynchronously write user input from a text box to a file.

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)
        {
            string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            StringBuilder sb = new StringBuilder();

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

            using (StreamWriter outfile = new StreamWriter(mydocpath + @"\UserInputFile.txt", true))
            {
                await outfile.WriteAsync(sb.ToString());
            }
        }
    }
}
Did you find this helpful?
(1500 characters remaining)
© 2013 Microsoft. All rights reserved.