w3resource

C#: Create a file in the disk newly

C# Sharp File Handling: Exercise-1 with Solution

Write a program in C# Sharp to create a blank file on the disk.

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 // Beginning of a try block to catch exceptions
        {
			Console.Write("\n\n Create a file named mytest.txt in the disk :\n"); // Displaying a message in the console
			Console.Write("------------------------------------------------\n"); // Displaying a separator line

            // 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 named mytest.txt in the disk :                                                                 
------------------------------------------------                                                              
 A file created with name mytest.txt

Flowchart:

Flowchart: C# Sharp Exercises - Create a file in the disk newly.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: C# Sharp File Handling Exercises.
Next: Write a program in C# Sharp to remove a file from the disk.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/file-handling/csharp-file-handling-exercise-1.php