Example from Troelsen
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace StringWriterReaderExample { class Program { static void Main(string[] args) { using (StringWriter sw = new StringWriter()) { sw.WriteLine("someLine"); StringBuilder sb = sw.GetStringBuilder(); sb.Insert(0, "Hey!"); Console.WriteLine("->{0}", sb.ToString()); sb.Remove(0, "Hey!".Length); Console.WriteLine("->{0}", sb.ToString()); using (StringReader sr = new StringReader(sw.ToString())) { string input = null; while ((input=sr.ReadLine())!=null) { Console.WriteLine(); } } Console.ReadLine(); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace StreamReadWrite { class Program { static void Main(string[] args) { // Get the directories currently on the C drive. DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories(); // Write each directory name to a file. using (StreamWriter sw = new StreamWriter("CDriveDirs.txt")) { foreach (DirectoryInfo dir in cDirs) { sw.WriteLine(dir.Name); } } // Read and show each line from the file. string line = ""; using (StreamReader sr = new StreamReader("CDriveDirs.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } } } |