C#: Remove a file from the disk
Write a program in C# Sharp to remove a file from 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
// Displaying a message to remove a file from the disk
Console.Write("\n\n Remove a file from the disk (at first create the file ) :\n");
Console.Write("--------------------------------------------------------------\n");
// Check if the file exists
if (File.Exists(fileName))
{
// If the file exists, delete it
File.Delete(fileName);
Console.WriteLine(" The file {0} deleted successfully.\n\n", fileName); // Displaying a message indicating successful file deletion
}
else
{
// If the file does not exist, display a message
Console.WriteLine(" File does not exist");
Console.ReadKey(); // Waits for a key press before exiting
}
}
}
Sample Output:
Remove a file from the disk (at first create the file ) : -------------------------------------------------------------- File does not exist
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a program in C# Sharp to create a blank file in the disk newly.
Next: Write a program in C# Sharp to create a blank file in the disk if the same file already exists.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics