delete a file in csharp

To delete a file in C#, we can use the File.Delete() method from the System.IO namespace. Here's an example:

main.cs
using System;
using System.IO;

class Program {
    static void Main(string[] args) {
        string filePath = @"C:\example\file.txt";

        try {
            File.Delete(filePath);
            Console.WriteLine("File deleted successfully.");
        } catch (IOException) {
            Console.WriteLine("Error occurred while accessing the file.");
        } catch (UnauthorizedAccessException) {
            Console.WriteLine("Permission denied to delete the file.");
        } catch (Exception ex) {
            Console.WriteLine("Error occurred while deleting the file: " + ex.Message);
        }
    }
}
613 chars
20 lines

In this code, we first specify the path of the file that we want to delete. Then, we use the File.Delete() method to delete the file.

It's important to use error handling while accessing and deleting files. In this example, we wrap the File.Delete() method in a try-catch block to handle any exceptions that may occur during the deletion process. We catch the IOException and UnauthorizedAccessException to handle file access and permission issues respectively, and any other exception is caught by the last catch block.

gistlibby LogSnag