w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Create a file with content in the disk

Secondary Nav

C# Sharp File Handling : Exercise-4 with Solution

Write a program in C# Sharp to create a file and add some text.
Expected Output :

 A file created with content name mytest.txt 

C# Sharp Code:

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

class filexercise2
{
    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 content in the disk :\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");
				 Console.WriteLine(" A file created with content name mytest.txt\n\n");
            }	            			
        }
        catch (Exception MyExcep)
        {
            Console.WriteLine(MyExcep.ToString());
        }
    }
}

C# Sharp Practice online:


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

class filexercise2
{
    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 content in the disk :\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");
				 Console.WriteLine(" A file created with content name mytest.txt\n\n");
            }	            			
        }
        catch (Exception MyExcep)
        {
            Console.WriteLine(MyExcep.ToString());
        }
    }
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.