How to: Write Characters to a String
.NET Framework 4.5
The following code examples write characters synchronously and asynchronously from a character array into a string.
The following example writes 5 characters synchronously from an array to a string.
using System; using System.IO; using System.Text; public class CharsToStr { public static void Main() { StringBuilder sb = new StringBuilder("Start with a string and add from "); char[] b = { 'c', 'h', 'a', 'r', '.', ' ', 'B', 'u', 't', ' ', 'n', 'o', 't', ' ', 'a', 'l', 'l' }; using (StringWriter sw = new StringWriter(sb)) { // Write five characters from the array into the StringBuilder. sw.Write(b, 0, 5); Console.WriteLine(sb); } } } // The example has the following output: // // Start with a string and add from char.
The next example reads all the characters asynchronously from a TextBox control, and stores them in an array. It then asynchronously writes each letter or white space character on a separate line followed by a line break to a TextBlock control.
using System; using System.Text; using System.Windows; using System.IO; namespace WpfApplication { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void ReadButton_Click(object sender, RoutedEventArgs e) { char[] charsRead = new char[UserInput.Text.Length]; using (StringReader reader = new StringReader(UserInput.Text)) { await reader.ReadAsync(charsRead, 0, UserInput.Text.Length); } StringBuilder reformattedText = new StringBuilder(); using (StringWriter writer = new StringWriter(reformattedText)) { foreach (char c in charsRead) { if (char.IsLetter(c) || char.IsWhiteSpace(c)) { await writer.WriteLineAsync(char.ToLower(c)); } } } Result.Text = reformattedText.ToString(); } } }