Search This Blog

Sunday 3 July 2016

Delete existing files in ASP.Net

using System.IO;

string filePath = Request.PhysicalApplicationPath + "Download\\";
DirectoryInfo dirInfo = new DirectoryInfo(filePath);
FileInfo[] fileInfo = dirInfo.GetFiles();

foreach (FileInfo file in fileInfo)
{
    string ext = file.Extension;
    if (ext == ".txt")
    {
        file.Delete();
    }
}

Note:-

Currently deleting only text files.
Delete all files in Download folder.

foreach (FileInfo file in fileInfo)
{
    file.Delete();
}

Delete only specified file in Download folder.

foreach (FileInfo file in fileInfo)
{
    string fileName = file.Name;
    if (fileName == "abc.txt")
    {
        file.Delete();
    }
}

Or

string filePath = Server.MapPath("~/Download") + "abc.txt";
if (File.Exists(filePath))
{
    File.Delete(filePath);
}

No comments:

Post a Comment