In this tutorial, I will show you a C # source code that he uses FileStream and StreamWriter to write to the file.
A Stream for a file, supporting both synchronous and asynchronous read and write operations.
A TextWriter is used for writing characters to a stream in a particular encoding.
The result is a text file with the contents: This is a line of text.
The following lines will be displayed in the program console:
1 2 | Hello World! Writer and file is close ! |
If you want to use encoding then you will have to add and modify with this source code in C#.
1 2 3 | using System.Text; ... writer = new StreamWriter(fileStream, Encoding.UTF8); |
Let’s see the source code:
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 | using System; using System.IO; namespace FileStreamStreamWriter { class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); FileStream fileStream; StreamWriter writer; TextWriter outputTextWriter = Console.Out; try { fileStream = new FileStream("stream.txt", FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter(fileStream); } catch (Exception e) { Console.WriteLine("Cannot open stream.txt for writing"); Console.WriteLine(e.Message); return; } Console.SetOut(writer); Console.WriteLine("This is a line of text"); Console.SetOut(outputTextWriter); writer.Close(); fileStream.Close(); Console.WriteLine("Writer and file is close !"); } } } |