Coder Perfect

How to delete a file after confirming its existence

Problem

How can I delete a file in C#, for example? C:test.txt, although it uses the same approach as batch files, e.g.

if exist "C:\test.txt"

delete "C:\test.txt"

else 

return nothing (ignore)

Asked by Tom

Solution #1

Using the File class, this is rather trivial.

if(File.Exists(@"C:\test.txt"))
{
    File.Delete(@"C:\test.txt");
}

Answered by Adam Lear

Solution #2

Use System.IO.File instead of System.IO.File. Delete as follows:

System.IO.File.Delete(@”C:\test.txt”)

From the documentation:

Answered by Chris Eberle

Solution #3

You can use the following command to import the System.IO namespace:

using System.IO;

If the filepath is the full path to the file, you can verify for its existence and remove it using the following command:

if(File.Exists(filepath))
{
     try
    {
         File.Delete(filepath);
    } 
    catch(Exception ex)
    {
      //Do something
    } 
}  

Answered by 4 revs, 3 users 70%

Solution #4

if (System.IO.File.Exists(@"C:\test.txt"))
    System.IO.File.Delete(@"C:\test.txt"));

but

System.IO.File.Delete(@"C:\test.txt");

will continue to do so as long as the folder is present.

Answered by Vercas

Solution #5

If you wish to avoid a DirectoryNotFoundException, make sure the file’s directory exists. This is done with File.Exists. Another option is to use the Path and Directory utility classes like follows:

string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
    File.Delete(file);
}

Answered by Derek W

Post is based on https://stackoverflow.com/questions/6391711/how-to-delete-a-file-after-checking-whether-it-exists