Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
How to Add Text in the RichTextBox in C#?
Next article icon

How to Read and Write a Text File in C#?

Last Updated : 01 Apr, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Termination of a program leads to the deletion of all data related to it. Therefore, we need to store the data somewhere. Files are used for permanently storing and sharing data. C# can be used to retrieve and manipulate data stored in text files. Reading a Text file: The file class in C# defines two static methods to read a text file namely File.ReadAllText() and File.ReadAllLines().
  • The File.ReadAllText() reads the entire file at once and returns a string. We need to store this string in a variable and use it to display the contents onto the screen.
  • The File.ReadAllLines() reads a file one line at a time and returns that line in string format. We need an array of strings to store each line. We display the contents of the file using the same string array.
There is another way to read a file and that is by using a StreamReader object. The StreamReader also reads one line at a time and returns a string. All of the above-mentioned ways to read a file are illustrated in the example code given below. csharp
// C# program to illustrate how  // to read a file in C# using System; using System.IO;  class Program {     static void Main(string[] args)     {         // Store the path of the textfile in your system         string file = @"M:\Documents\Textfile.txt";          Console.WriteLine("Reading File using File.ReadAllText()");          // To read the entire file at once         if (File.Exists(file)) {             // Read all the content in one string             // and display the string             string str = File.ReadAllText(file);             Console.WriteLine(str);         }         Console.WriteLine();          Console.WriteLine("Reading File using File.ReadAllLines()");          // To read a text file line by line         if (File.Exists(file)) {             // Store each line in array of strings             string[] lines = File.ReadAllLines(file);              foreach(string ln in lines)                 Console.WriteLine(ln);         }         Console.WriteLine();          Console.WriteLine("Reading File using StreamReader");          // By using StreamReader         if (File.Exists(file)) {             // Reads file line by line             StreamReader Textfile = new StreamReader(file);             string line;              while ((line = Textfile.ReadLine()) != null) {                 Console.WriteLine(line);             }              Textfile.Close();              Console.ReadKey();         }         Console.WriteLine();     } } 
To run this program, save the file with .cs extension and then can execute using csc filename.cs command on cmd. Or you can use the Visual Studio. Here, we have a text file named as Textfile.txt which have the content shown in the output. Output: reading text file in C# Writing a Text File: The File class in C# defines two static methods to write a text file namely File.WriteAllText() and File.WriteAllLines().
  • The File.WriteAllText() writes the entire file at once. It takes two arguments, the path of the file and the text that has to be written.
  • The File.WriteAllLines() writes a file one line at a time. It takes two arguments, the path of the file and the text that has to be written, which is a string array.
There is another way to write to a file and that is by using a StreamWriter object. The StreamWriter also writes one line at a time. All of the three writing methods create a new file if the file doesn't exist, but if the file is already present in that specified location then it is overwritten. All of the above-mentioned ways to write to a text file are illustrated in the example code given below. csharp
// C# program to illustrate how  // to write a file in C# using System; using System.IO;  class Program {     static void Main(string[] args)     {         // Store the path of the textfile in your system         string file = @"M:\Documents\Textfile.txt";          // To write all of the text to the file         string text = "This is some text.";         File.WriteAllText(file, text);          // To display current contents of the file         Console.WriteLine(File.ReadAllText(file));         Console.WriteLine();          // To write text to file line by line         string[] textLines1 = { "This is the first line",                                 "This is the second line",                               "This is the third line" };          File.WriteAllLines(file, textLines1);          // To display current contents of the file         Console.WriteLine(File.ReadAllText(file));          // To write to a file using StreamWriter         // Writes line by line         string[] textLines2 = { "This is the new first line",                              "This is the new second line" };          using(StreamWriter writer = new StreamWriter(file))         {             foreach(string ln in textLines2)             {                 writer.WriteLine(ln);             }         }         // To display current contents of the file         Console.WriteLine(File.ReadAllText(file));          Console.ReadKey();     } } 
To run this program, save the file with .cs extension and then can execute using csc filename.cs command on cmd. Or you can use the Visual Studio. Output: writing a file in C# In case you want to add more text to an existing file without overwriting the data already stored in it, you can use the append methods provided by the File class of System.IO. csharp
using System; using System.IO;  class Program {     static void Main(string[] args)     {         // Store the path of the textfile in your system         string file = @"M:\Documents\Textfile.txt";          // To write all of the text to the file         string text1 = "This is some text.";         File.WriteAllText(file, text1);          // To append text to a file         string text2 = "This is text to be appended";         File.AppendAllText(file, text2);          // To display current contents of the file         Console.WriteLine(File.ReadAllText(file));         Console.ReadKey();     } } 
Output: appending text in a file in C#

Next Article
How to Add Text in the RichTextBox in C#?

M

ManasiKirloskar
Improve
Article Tags :
  • Programming Language
  • C#
  • CSharp-File-Handling

Similar Reads

  • C# Program to View the Access Date and Time of a File
    Given a file, our task is to view the date and time of access to a file. So to do this we use the following properties of the FileSystemInfo class: 1. CreationTime: This property is used to get the time in which the file is created. Syntax: file.CreationTime Where the file is the path of the file an
    2 min read
  • How to Add Text in the RichTextBox in C#?
    In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In
    3 min read
  • How to set the Text in TextBox in C#?
    In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the text associated with the TextBox by using the Text property of the TextBox. In Windows form
    3 min read
  • File.ReadAllText(String) Method in C# with Examples
    File.ReadAllText(String) is an inbuilt File class method that is used to open a text file then reads all the text in the file and then closes the file.Syntax:   public static string ReadAllText (string path); Parameter: This function accepts a parameter which is illustrated below:   path: This is th
    2 min read
  • File.OpenText() Method in C# with Examples
    File.OpenText(String) is an inbuilt File class method which is used to open an existing UTF-8 encoded text file for reading.Syntax:   public static System.IO.StreamReader OpenText (string path); Parameter: This function accepts a parameter which is illustrated below:   path: This is the specified te
    2 min read
  • File.ReadAllText(String, Encoding) Method in C# with Examples
    File.ReadAllText(String, Encoding) is an inbuilt File class method that is used to open a text file then reads all the text in the file with the specified encoding and then closes the file.Syntax:   public static string ReadAllText (string path, System.Text.Encoding encoding); Parameter: This functi
    2 min read
  • How to create Multiline TextBox in C#?
    In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to create a multiline TextBox which stores multiple lines of the content using Multiline property of t
    3 min read
  • File.AppendText() Method in C# with Examples
    File.AppendText() is an inbuilt File class method which is used to create a StreamWriter that appends UTF-8 encoded text to an existing file else it creates a new file if the specified file does not exist.Syntax:   public static System.IO.StreamWriter AppendText (string path); Parameter: This functi
    3 min read
  • File.ReadLines(String) Method in C# with Examples
    File.ReadLines(String) is an inbuilt File class method that is used to read the lines of a file. Syntax: public static System.Collections.Generic.IEnumerable ReadLines (string path); Parameter: This function accepts a parameter which is illustrated below: path: This is the specified file for reading
    2 min read
  • File.OpenRead() Method in C# with Examples
    File.OpenRead(String) is an inbuilt File class method which is used to open an existing file for reading.Syntax:   public static System.IO.FileStream OpenRead (string path); Parameter: This function accepts a parameter which is illustrated below:   path: This is the specified file which is going to
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences