Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a file after checking whether it exists

Tags:

c#

.net

windows

People also ask

How do you delete files that do not exist?

Right click the bad file and click Add to Archives. Then in the options select to delete original file after compression. Leave other options same and proceed. Bad file will be deleted and a compressed file will be created in its place.

How do you delete a file if exists in Python?

To delete a file if exists in Python, use the os. path. exists() and os. remove() method.

How do you delete a file if already exists in C#?

Delete(path) method is used to delete a file in C#. The File. Delete() method takes the full path (absolute path including the file name) of the file to be deleted. If file does not exist, no exception is thrown.


This is pretty straightforward using the File class.

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


As Chris pointed out in the comments, you don't actually need to do the File.Exists check since File.Delete doesn't throw an exception if the file doesn't exist, although if you're using absolute paths you will need the check to make sure the entire file path is valid.

Use System.IO.File.Delete like so:

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

From the documentation:

If the file to be deleted does not exist, no exception is thrown.


You could import the System.IO namespace using:

using System.IO;

If the filepath represents the full path to the file, you can check its existence and delete it as follows:

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

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

but

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

will do the same as long as the folder exists.


If you want to avoid a DirectoryNotFoundException you will need to ensure that the directory of the file does indeed exist. File.Exists accomplishes this. Another way would be to utilize the Path and Directory utility classes like so:

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

  if (System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
    {
        // Use a try block to catch IOExceptions, to 
        // handle the case of the file already being 
        // opened by another process. 
        try
        {
            System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
            return;
        }
    }

if (File.Exists(path))
{
    File.Delete(path);
}