How to delete a file after checking whether it exists

C#.NetWindows

C# Problem Overview


How can I delete a file in C# e.g. C:\test.txt, although apply the same kind of method like in batch files e.g.

if exist "C:\test.txt"

delete "C:\test.txt"

else 

return nothing (ignore)

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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
    } 
}  

Solution 4 - C#

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.

Solution 5 - C#

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);
}

Solution 6 - C#

  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;
        }
    }

Solution 7 - C#

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

Solution 8 - C#

If you are reading from that file using FileStream and then wanting to delete it, make sure you close the FileStream before you call the File.Delete(path). I had this issue.

var filestream = new System.IO.FileStream(@"C:\Test\PutInv.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(@"C:\Test\PutInv.txt");

Solution 9 - C#

if (File.Exists(Path.Combine(rootFolder, authorsFile)))    
{    
// If file found, delete it    
File.Delete(Path.Combine(rootFolder, authorsFile));    
Console.WriteLine("File deleted.");    
} 

Dynamic

 string FilePath = Server.MapPath(@"~/folder/news/" + IdSelect)
 if (System.IO.File.Exists(FilePath + "/" + name+ ".jpg"))
   {
    System.IO.File.Delete(FilePath + "/" + name+ ".jpg");
   }

Delete all files in a directory

string[] files = Directory.GetFiles(rootFolder);    
foreach (string file in files)    
{    
File.Delete(file);    
Console.WriteLine($"{file} is deleted.");    
}

Solution 10 - C#

Sometimes you want to delete a file whatever the case(whatever the exception occurs ,please do delete the file). For such situations.

public static void DeleteFile(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            bool isDeleted = false;
            while (!isDeleted)
            {
                try
                {
                    File.Delete(path);
                    isDeleted = true;
                }
                catch (Exception e)
                {
                }
                Thread.Sleep(50);
            }
        }

Note:An exception is not thrown if the specified file does not exist.

Solution 11 - C#

This will be the simplest way,

if (System.IO.File.Exists(filePath)) 
{
  System.IO.File.Delete(filePath);
  System.Threading.Thread.Sleep(20);
}

Thread.sleep will help to work perfectly, otherwise, it will affect the next step if we doing copy or write the file.

Another way I did is,

if (System.IO.File.Exists(filePath))
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(filePath);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - C#Adam LearView Answer on Stackoverflow
Solution 2 - C#Chris EberleView Answer on Stackoverflow
Solution 3 - C#AshinView Answer on Stackoverflow
Solution 4 - C#VercasView Answer on Stackoverflow
Solution 5 - C#Derek WView Answer on Stackoverflow
Solution 6 - C#Ahmed GhazeyView Answer on Stackoverflow
Solution 7 - C#ecModeView Answer on Stackoverflow
Solution 8 - C#ag93View Answer on Stackoverflow
Solution 9 - C#mirazimiView Answer on Stackoverflow
Solution 10 - C#Hameed SyedView Answer on Stackoverflow
Solution 11 - C#Aniyan KolathurView Answer on Stackoverflow