Read from and write to a text file by Visual C# - C# (2024)

  • Article

This article helps you read from and write to a text file by using Visual C#.

Original product version: Visual Studio
Original KB number: 816149

Summary

The Read a text file section of this article describes how to use the StreamReader class to read a text file. The Write a text file (example 1) and the Write a text file (example 2) sections describe how to use the StreamWriter class to write text to a file.

Read a text file

The following code uses the StreamReader class to open, to read, and to close the text file. You can pass the path of a text file to the StreamReader constructor to open the file automatically. The ReadLine method reads each line of text, and increments the file pointer to the next line as it reads. When the ReadLine method reaches the end of the file, it returns a null reference. For more information, see StreamReader Class.

  1. Create a sample text file in Notepad. Follow these steps:

    1. Paste the hello world text in Notepad.
    2. Save the file as Sample.txt.
  2. Start Microsoft Visual Studio.

  3. On the File menu, point to New, and then select Project.

  4. Select Visual C# Projects under Project Types, and then select Console Application under Templates.

  5. Add the following code at the beginning of the Class1.cs file:

    using System.IO;
  6. Add the following code to the Main method:

    String line;try{ //Pass the file path and file name to the StreamReader constructor StreamReader sr = new StreamReader("C:\\Sample.txt"); //Read the first line of text line = sr.ReadLine(); //Continue to read until you reach end of file while (line != null) { //write the line to console window Console.WriteLine(line); //Read the next line line = sr.ReadLine(); } //close the file sr.Close(); Console.ReadLine();}catch(Exception e){ Console.WriteLine("Exception: " + e.Message);}finally{ Console.WriteLine("Executing finally block.");}
  7. On the Debug menu, select Start to compile and to run the application. Press ENTER to close the Console window. The Console window displays the contents of the Sample.txt file:

    Hello world

Write a text file (example 1)

The following code uses the StreamWriter class to open, to write, and to close the text file. In a similar way to the StreamReader class, you can pass the path of a text file to the StreamWriter constructor to open the file automatically. The WriteLine method writes a complete line of text to the text file.

  1. Start Visual Studio.

  2. On the File menu, point to New, and then select Project.

  3. Select Visual C# Projects under Project Types, and then select Console Application under Templates.

  4. Add the following code at the beginning of the Class1.cs file:

    using System.IO;
  5. Add the following code to the Main method:

    try{ //Pass the filepath and filename to the StreamWriter Constructor StreamWriter sw = new StreamWriter("C:\\Test.txt"); //Write a line of text sw.WriteLine("Hello World!!"); //Write a second line of text sw.WriteLine("From the StreamWriter class"); //Close the file sw.Close();}catch(Exception e){ Console.WriteLine("Exception: " + e.Message);}finally{ Console.WriteLine("Executing finally block.");}
  6. On the Debug menu, select Start to compile and to run the application. This code creates a file that is named Test.txt on drive C. Open Test.txt in a text editor such as Notepad. Test.txt contains two lines of text:

    Hello World!!From the StreamWriter class

Write a text file (example 2)

The following code uses the StreamWriter class to open, to write, and to close the text file. Unlike the previous example, this code passes two additional parameters to the constructor. The first parameter is the file path and the file name of the file. The second parameter, true, specifies that the file is opened in append mode. If you specify false for the second parameter, the contents of the file are overwritten each time you run the code. The third parameter specifies Unicode, so that StreamWriter encodes the file in Unicode format. You can also specify the following encoding methods for the third parameter:

  • ASC11
  • Unicode
  • UTF7
  • UTF8

The Write method is similar to the WriteLine method, except that the Write method doesn't automatically embed a carriage return or line feed (CR/LF) character combination. It's useful when you want to write one character at a time.

  1. Start Visual Studio.

  2. On the File menu, point to New, and then click Project.

  3. Click Visual C# Projects under Project Types, and then click Console Application under Templates.

  4. Add the following code at the beginning of the Class1.cs file:

    using System.IO;using System.Text;
  5. Add the following code to the Main method:

    Int64 x;try{ //Open the File StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII); //Write out the numbers 1 to 10 on the same line. for(x=0; x < 10; x++) { sw.Write(x); } //close the file sw.Close();}catch(Exception e){ Console.WriteLine("Exception: " + e.Message);}finally{ Console.WriteLine("Executing finally block.");}
  6. On the Debug menu, select Start to compile and to run the application. This code creates a file that is named Test1.txt on drive C. Open Test1.txt in a text editor such as Notepad. Test1.txt contains a single line of text: 0123456789.

Complete code listing for how to read a text file

//Read a Text Fileusing System;using System.IO;namespace readwriteapp{ class Class1 { [STAThread] static void Main(string[] args) { String line; try { //Pass the file path and file name to the StreamReader constructor StreamReader sr = new StreamReader("C:\\Sample.txt"); //Read the first line of text line = sr.ReadLine(); //Continue to read until you reach end of file while (line != null) { //write the line to console window Console.WriteLine(line); //Read the next line line = sr.ReadLine(); } //close the file sr.Close(); Console.ReadLine(); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } finally { Console.WriteLine("Executing finally block."); } } }}

Complete code listing for how to write a text file (version 1)

//Write a text file - Version-1using System;using System.IO;namespace readwriteapp{ class Class1 { [STAThread] static void Main(string[] args) { try { //Pass the filepath and filename to the StreamWriter Constructor StreamWriter sw = new StreamWriter("C:\\Test.txt"); //Write a line of text sw.WriteLine("Hello World!!"); //Write a second line of text sw.WriteLine("From the StreamWriter class"); //Close the file sw.Close(); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } finally { Console.WriteLine("Executing finally block."); } } }}

Complete code listing for how to write a text file (version 2)

//Write a text file - Version 2using System;using System.IO;using System.Text;namespace readwriteapp{ class Class1 { [STAThread] static void Main(string[] args) { Int64 x; try { //Open the File StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII); //Writeout the numbers 1 to 10 on the same line. for(x=0; x < 10; x++) { sw.Write(x); } //close the file sw.Close(); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } finally { Console.WriteLine("Executing finally block."); } } }}

Troubleshoot

For all file manipulations, it's good programming practice to wrap the code inside a try-catch-finally block to handle errors and exceptions. Specifically, you may want to release handles to the file in the final block so that the file isn't locked indefinitely. Some possible errors include a file that doesn't exist, or a file that is already in use.

Read from and write to a text file by Visual C# - C# (2024)

FAQs

How to read text from a text file in C#? ›

To read text files in C# programming language, you'll need to use the StreamReader class. Here is an example: StreamReader reader = new StreamReader("file. txt"); string line = ""; while ((line = reader.

How to write string to text file in C#? ›

File. WriteAllText(String, String) is an inbuilt File class method that is used to create a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

How to write an object to a text file in C#? ›

Write to a text file in C# using the File class

WriteAllLines method writes a string array to a file. If the file is not created, it creates a new file. If the file is already created, it will overwrite the existing file. Once file writing is done, it closes the file.

How to read and write string from file in C? ›

To read from a text file, you follow these steps:
  1. First, open the text file using the fopen() function.
  2. Second, use the fgets() or fgetc() function to read text from the file.
  3. Third, close the file using the fclose() function.

How to read and write data from CSV file in C#? ›

How to Read a CSV File in C#
  1. Download and install the C# CSV reading library.
  2. Create a C# or VB project.
  3. Add the code example from this page to your project.
  4. In the code, specify the path to the CSV, and the output name & file format.
  5. Run the C# project to view the document.

How to get text from string in C#? ›

You call the Substring(Int32) method to extract a substring from a string that begins at a specified character position and ends at the end of the string. The starting character position is zero-based; in other words, the first character in the string is at index 0, not index 1.

How do you add a string to text in C#? ›

6 Effective Ways To Concatenate Strings In C#
  1. Use of + operator.
  2. Use of String Interpolation.
  3. Use of String.Concatenate() method.
  4. Use of String.Join() method.
  5. Use of String.Format() method.
  6. Use of StringBuilder.Append() method.
May 29, 2024

How to write a string array to a text file in C#? ›

WriteAllLines(String, String[], Encoding) Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.

How to format text in Visual Studio C#? ›

To set up formatting rules for the script Editor: In Visual Studio for Windows, navigate to Tools > Options, then locate Text Editor > C# > Code Style Formatting. Use the settings to modify the General, Indentation, New Lines, Spacing, and Wrapping options.

How to read and write Excel file in C#? ›

Steps to read and write data from Excel using C#
  1. Step 1: Create a new C# project in Visual Studio. ...
  2. Step 2: Add COM Component Reference i.e. Excel 14 Object. ...
  3. Step 3: Import the namespaces in C# code. ...
  4. Step 4: Write Data to Excel File. ...
  5. Step 5: Read Data from Excel File. ...
  6. Step 6: Run the C# Program.
Mar 6, 2023

How to read and store data from a file in C? ›

File Input and Output in C
  1. Create a variable to represent the file.
  2. Open the file and store this "file" with the file variable.
  3. Use the fprintf or fscanf functions to write/read from the file.

How to read the details of a file in C#? ›

The File class provides two static methods to read a text file in C#. The File. ReadAllText() method opens a text file, reads all the text in the file into a string, and then closes the file. The following code reads a text file into a string.

How to read and write data from JSON file in C#? ›

First, we use a StreamReader object to read the contents of the JSON file into a string variable called json . Next, we invoke the JArray. Parse() method and pass the JSON string to it. This method parses the string into a JArray object, which is a collection of JToken objects representing the data in the JSON file.

References

Top Articles
The Boys in the Boat | Rotten Tomatoes
Shade-Erase Under Eye Serum
LAC-318900 - Wildfire and Smoke Map
Corgsky Puppies For Sale
Sallisaw Bin Store
The Fappening Blgo
Provider Connect Milwaukee
Gma Deals And Steals December 5 2022
How Much Food Should I Buy For Christmas? | Gousto Christmas
Retail Jobs For Teens Near Me
Adventhealth Employee Hub Login
Myud Dbq
Magma Lozenge Location
Foodsmart Jonesboro Ar Weekly Ad
Anchor Martha MacCallum Talks Her 20-Year Journey With FOX News and How She Stays Grounded (EXCLUSIVE)
Anchoring in Masonry Structures – Types, Installation, Anchorage Length and Strength
Scholar Dollar Nmsu
Jennifer Paeyeneers Wikipedia
All classes in Pathfinder: Wrath of the Righteous
Build it online for your customers – a new way to do business with Dell | Dell
FREE Printable Pets Animal Playdough Mats
suggest - Englisch-Deutsch Übersetzung | PONS
Liquor Barn Redding
Monahan's By The Cove Charlestown Menu
Poe Poison Srs
phoenix health/wellness services - craigslist
Aflac Dulles Synergy
Craigslist St. Paul
Ethos West Mifflin
7148646793
Rooftop Snipers Unblocked Games Premium
Winsipedia
Mikayla Campinos: The Rising Star Of EromeCom
Woude's Bay Bar Photos
Adaptibar Vs Uworld
Today's Final Jeopardy Clue
Xxn Abbreviation List 2023
Chets Rental Chesterfield
18006548818
Dollar Tree Aktie (DLTR) • US2567461080
Rubmd.com.louisville
Bostick Thompkins Funeral Home
NCCAC
Stellaris Archaeological Site
Trực tiếp bóng đá Hà Nội vs Bình Định VLeague 2024 hôm nay
Dawat Restaurant Novi
Potomac Edison Wv Outages
Watermelon Cucumber Basil Lemonade - Wine a Little, Cook a Lot
Walgreens Bunce Rd
Joann Stores Near Me
Unblocked Games Premium 77
Pollen Count Butler Pa
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 6039

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.