275

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)

11 Answers 11

470

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.

6
  • 18
    That test isn't actually needed. See my post. Commented Jun 17, 2011 at 20:57
  • 30
    The test is necessary if you want to prevent a possible DirectoryNotFoundException. Commented Jun 17, 2011 at 21:04
  • 8
    The test shouldn't be used in place of exception handling tho, but rather in conduction with it. Any number of scenarios can result in the exists check returning true and Delete throwing.
    – Josh
    Commented Jun 23, 2011 at 4:09
  • 3
    Why's there an @ before the file path? For me it works without.
    – Pascal
    Commented Feb 10, 2017 at 13:38
  • 8
    @ keeps you from having to double up the backslashes.
    – PRMan
    Commented Feb 21, 2017 at 0:34
134

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.

7
  • 11
    That will throw a DirectoryNotFoundException if "The specified path is invalid (for example, it is on an unmapped drive)." Commented Jun 17, 2011 at 21:02
  • 6
    How odd. Intellisense says An exception is thrown if the specified file does not exist. Commented Aug 22, 2011 at 15:24
  • 1
    Perhaps you're using a different version of the .NET framework? Commented Aug 22, 2011 at 17:22
  • 2
    I'm using .Net4, it looks like the intellisense is wrong I have run a check and no exception is thrown Commented Aug 23, 2011 at 8:22
  • 5
    Yeah I tried and just System.IO.File.Delete(@"C:\test.txt"); is enough. Thanks Commented Dec 17, 2012 at 13:17
49

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
    } 
}  
2
  • 4
    Why not just issue the Delete call regardless and catch any exception that indicates that the file didn't exist?
    – antred
    Commented May 23, 2018 at 12:16
  • 4
    There are more exceptions that can be thrown, I suppose.
    – Rev Tyler
    Commented Nov 16, 2020 at 17:24
34
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.

27

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);
}
17
  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;
        }
    }
15
if (File.Exists(path))
{
    File.Delete(path);
}
0
4

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");
1
  • 1
    Or use a using statement, where the File.Delete() would go outside the brackets. In the example you have, you should also do a filestream.Dispose();.
    – vapcguy
    Commented Oct 18, 2017 at 23:07
4
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.");    
}
1

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.

3
  • 15
    So you are trying to delete file 20 times per second until it's deleted. What if, for some reason, file can't be deleted and program will try to delete it forever? I don't think this is good solution.
    – kv1dr
    Commented Feb 14, 2018 at 12:18
  • 5
    At the very least, you should provide a timeout parameter.
    – antred
    Commented May 23, 2018 at 12:14
  • 1
    @kv1dr right. I think you should try for a limited time and return a failure message if the file wasn't deleted.
    – QMaster
    Commented Dec 29, 2019 at 20:40
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.