Delete a file with C#
This post will discuss how to delete a file using C#.
In C#, we can use the File.Delete() method for deleting a given file. It takes a single argument – relative or absolute path of the file to be deleted without any wildcard characters.
This method throws a DirectoryNotFoundException if the specified path is invalid and an IOException when the specified file is in use. It doesn’t throw an exception when a file deletion fails.
The following example first checks if a specified file exists using File.Exists. The File.Delete() method is called then if the file is present.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.IO; public class Example { public static void Main() { string fileName = @"C:\some\path\somefile.txt"; if (File.Exists(fileName)) { try { File.Delete(fileName); } catch (Exception e) { Console.WriteLine("The deletion failed: {0}", e.Message); } } else { Console.WriteLine("Specified file doesn't exist"); } } } /* Output: ABC */ |
Since the File.Delete() method doesn’t throw an exception if the file doesn’t exist, there is no need to check for the file’s existence. We can simplify the code as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.IO; public class Example { public static void Main() { string fileName = @"C:\some\path\somefile.txt"; try { File.Delete(fileName); } catch (Exception e) { Console.WriteLine("The deletion failed: {0}", e.Message); } } } |
We can also use an instance of the FileInfo class to delete a file in C#. Its Delete() method works similarly to the File.Delete() method discussed above.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.IO; public class Example { public static void Main() { string fileName = @"C:\some\path\somefile.txt"; try { FileInfo file = new FileInfo(fileName); file.Delete(); } catch (Exception e) { Console.WriteLine("The deletion failed: {0}", e.Message); } } } |
To delete the directory and all its subdirectories, the Directory.Delete() method can be used, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\some\path"; try { Directory.Delete(path); } catch (Exception e) { Console.WriteLine("The deletion failed: {0}", e.Message); } } } |
That’s all about deleting a file with C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)