w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Create a file in the disk if it is exists

Secondary Nav

C# Sharp File Handling : Exercise-3 with Solution

Write a program in C# Sharp to create a blank file in the disk if the same file already exists.
Expected Output :

 A file created with name mytest.txt  

C# Sharp Code:

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

class filexercise1
{
    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 in the disk if it is exists:\n");
			Console.Write("-----------------------------------------------\n");
            // Create the file.
            using (FileStream fileStr = File.Create(fileName))
            {
                Console.WriteLine(" A file created with 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 filexercise1
{
    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 in the disk if it is exists:\n");
			Console.Write("-----------------------------------------------\n");
            // Create the file.
            using (FileStream fileStr = File.Create(fileName))
            {
                Console.WriteLine(" A file created with 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.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program