Lahib
Lahib

Reputation: 1365

Search for filename on Server

Im creating a website where it is possible to uploade an excel file end extract data from it. In my code i uploade the excel file to the application on the server in an Uploade folder and extract data from it.

I am renaming the filename to a string with date and time so i delete files that is not matching the string i get from DateTime.Now since i dont wanna fill my server with excel files.

So i want to check for existing files in the Uploade folder on my server, and if there is older excel files i want to delete them.

How do i get the folder content from my server ?

My code:

protected void uploadButton_Click(object sender, EventArgs e)
{
    if (fileUpload.HasFile)
    {
        string fileuploaded = Server.MapPath("Upload") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "excel" + Path.GetExtension(fileUpload.FileName);
        fileUpload.SaveAs(fileuploaded);
    }

}

Upvotes: 2

Views: 254

Answers (2)

VMAtm
VMAtm

Reputation: 28355

You can use the Directory.GetFiles method for this:

string folder = Server.MapPath("Upload");
foreach (var filePath in Directory.GetFiles(folder, "*excel*"), SearchOption.TopDirectoryOnly)
{
    FileInfo fi = new FileInfo(filePath);
    if ((DateTime.Now - fi.CreationTime).TotalDays > 30)
    {
        File.Delete(filePath);
    }
}

You also can parse the creation date from the filename using DateTime.ParseExact().

Upvotes: 2

Gregor Primar
Gregor Primar

Reputation: 6805

string folder = Server.MapPath("Upload");
foreach (var item in Directory.GetFiles(folder))
{
    FileInfo fi = new FileInfo(item);
    DateTime creationDate = fi.CreationTime;
    //TODO: check creation date and delete files you want...

}

Upvotes: 2

Related Questions