- This topic explains about how to read text file and write text file in C# programming.
- This is done with the help of stream reader and stream writer.
- Tools needed: TextBox1 (TextBox1), Button1 (Button1), Button2 (Button2)
System.IO Namespace – Read text file and write text file in C#
- The System.IO namespace contains types that allow read text file and write text file and data streams and types that provide basic file and directory support.
StreamReader Class – Read text file and write text file in C#
- Implements a TextReader that reads characters from a byte stream in a particular encoding.
- Syntax for StreamReader Class
|
1 2 3 4 5 |
// Declaration [SerializableAttribute()] [ComVisibleAttribute(true)] public class StreamReader : TextReader { } |
StreamWriter Class – Read text file and write text file in C#
- Implement a TextWriter for writing characters to a stream in a particular encoding.
- Syntax for StreamWriter Class
|
1 2 3 4 5 |
// Declaration [SerializableAttribute()] [ComVisibleAttribute(true)] public class StreamWriter : TextWriter { } |
StreamReader.ReadToEnd Method – Read text file and write text file in C#
- Help to reads all characters from the current position to the end of the stream.
Read text file and write text file in C# – Complete 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { try { string file_name = "C:/text.txt"; // Application.StartupPath() & "/text.dat" System.IO.StreamReader stream_reader = new System.IO.StreamReader(file_name); try { TextBox1.Text = stream_reader.ReadToEnd(); TextBox1.Select(0, 0); } finally { stream_reader.Close(); } } catch (System.IO.FileNotFoundException exc) { // Ignore this error. } catch (Exception exc) { // Report other errors. MessageBox.Show(exc.Message, "Read " + "Error"); } } private void button2_Click(object sender, EventArgs e) { try { string file_name = "C:/text.txt"; // Application.StartupPath() & "/text.dat" System.IO.StreamReader stream_reader = new System.IO.StreamReader(file_name); try { TextBox1.Text = stream_reader.ReadToEnd(); TextBox1.Select(0, 0); } finally { stream_reader.Close(); } } catch (System.IO.FileNotFoundException exc) { // Ignore this error. } catch (Exception exc) { // Report other errors. MessageBox .Show (exc.Message, "Read " + "Error"); } } } } |
Read text file and write text file in C#







