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
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# .
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly