How to delete a file, after checking if it exists or not using C#?


I would like to know, how can I delete a file, after checking if it exists on the hard disk, if yes, then delete it, using C# in asp.net?

Thanks


Asked by:- neena
1
: 4607 At:- 1/17/2019 12:31:34 PM
C# ASP.NET Delete a file using C#







2 Answers
profileImage Answered by:- Vinnu

Using System.IO.File class you can check if file exists or not, then delete it in C#, as below

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

You can also read the detailed about File Input / Output in C# .

1
At:- 1/18/2019 3:36:46 PM
Thank you, works as needed. 0
By : neena - at :- 1/31/2019 9:37:25 AM


profileImage Answered by:- vikas_jk

You can also simply use System.IO.File.Delete(@"C:\test.txt") to delete file in C#, since it doesn't throw exception even when files doesn't exists.

But it will throw an DirectoryNotFoundException exception if "The specified path is invalid (for example, if the folder doesn't exist).

OR

If the filepath represents the full path to the file, then you can use below code to check if file exists and then delete it.

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

This will require you to use "System.IO" namespace.

0
At:- 4/26/2022 3:24:04 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use