Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Create a file with text and read the file

C# Sharp File Handling: Exercise-5 with Solution

Write a program in C# Sharp to create a file with text and read the file.

Sample Solution:-

C# Sharp Code:

using System;
using System.IO;
using System.Text;

class filexercise3
{
    public static void Main()
    {
        string fileName = @"mytest.txt"; 

        try
        {
            // Delete the file if it exists.
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
			Console.Write("\n\n Create a file with text and read the file  :\n");
			Console.Write("-------------------------------------------------\n");            
            // Create the file.
            using (StreamWriter fileStr = File.CreateText(fileName)) 
            {
                fileStr.WriteLine(" Hello and Welcome");
                fileStr.WriteLine(" It is the first content");
                fileStr.WriteLine(" of the text file mytest.txt");
            }	            
            using (StreamReader sr = File.OpenText(fileName))
            {
                string s = "";
				Console.WriteLine(" Here is the content of the file mytest.txt : ");
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
                Console.WriteLine("");
            }
        }
        catch (Exception MyExcep)
        {
            Console.WriteLine(MyExcep.ToString());
        }
    }
}

Sample Output:

Create a file with text and read the file  :                                                                 
-------------------------------------------------                                                             
 Here is the content of the file mytest.txt :                                                                 
 Hello and Welcome                                                                                            
 It is the first content                                                                                      
 of the text file mytest.txt 

Flowchart :

Flowchart: C# Sharp Exercises - Create a file with text and read the file

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to create a file and add some text.
Next: Write a program in C# Sharp to create a file and write an array of strings to the file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.