w3resource

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

C# Sharp File Handling: Exercise-3 with Solution

Write a C# Sharp program to create a blank file on the disk if the same file already exists.

Sample Solution:-

C# Sharp Code:

using System; // Importing the System namespace
using System.IO; // Importing the System.IO namespace for file operations
using System.Text; // Importing the System.Text namespace for encoding

class filexercise1 // Declaring a class named filexercise1
{
    public static void Main() // Declaring the Main method
    {
        string fileName = @"mytest.txt"; // Initializing a string variable with the file name

        try // Starting a try block to catch exceptions
        {
            // Delete the file if it exists.
            if (File.Exists(fileName)) // Checking if the file exists
            {
                File.Delete(fileName); // If the file exists, delete it
            }

            // Displaying a message to create a file in the disk if it exists
            Console.Write("\n\n Create a file in the disk if it exists:\n");
            Console.Write("-----------------------------------------------\n");

            // Create the file.
            using (FileStream fileStr = File.Create(fileName)) // Creating a FileStream to create the file
            {
                Console.WriteLine(" A file created with name mytest.txt\n\n"); // Displaying a message indicating successful file creation
            }
        }
        catch (Exception MyExcep) // Catching any exceptions that might occur
        {
            Console.WriteLine(MyExcep.ToString()); // Displaying the exception details if any
        }
    }
}

Sample Output:

 Create a file in the disk if it is exists:                                                                   
-----------------------------------------------                                                               
 A file created with name mytest.txt 

Flowchart:

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

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to remove a file from the disk.
Next: Write a program in C# Sharp to create a file and add some text.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.