Share via


delete files in folder older than 1 hour...runs itself

Question

Wednesday, May 25, 2011 5:13 AM

I'm looking for a script that runs itself without the user interacting with it.

Ideally it would reside in the folder that it has to run.

it would delete any file older than 1 hour.

I have a script that deletes anything older than 1hour but the user has to initialse it.

Is this possible?

 

Thanks

All replies (21)

Wednesday, May 25, 2011 8:19 AM ✅Answered

One thing that will work for sure is this solution.

 

Whenever a user uploads a file, create a session object that will contain the file name.

There is a method in Global.asax file called Session_End. This method is executed when a user session is expiring.

Normally the session times out after 20 minutes but you can change it so that it expires in 1 hour.

 

So exactly after 1 hour, the Session_End method will execute automatically. You can delete the file in this method.

 

Code : 

 

At File UPload

Session["FileUploaded"]=FileName;

 

At Session_End event

File.Delete(Session["FileUploaded"].ToString());

Let me know if you need any more help.


Wednesday, May 25, 2011 9:22 AM ✅Answered

One thing that will work for sure is this solution.

 

Whenever a user uploads a file, create a session object that will contain the file name.

There is a method in Global.asax file called Session_End. This method is executed when a user session is expiring.

Normally the session times out after 20 minutes but you can change it so that it expires in 1 hour.

 

So exactly after 1 hour, the Session_End method will execute automatically. You can delete the file in this method.

 

Code : 

 

At File UPload

 

Session["FileUploaded"]=FileName;

 

 

At Session_End event

 

File.Delete(Session["FileUploaded"].ToString());

 

Let me know if you need any more help.

 

 

I created the Session variable, added sessionState to web.config and the global.asax session_end but it doesn't seem to be firing, it is on my local machine?

 

Session["PDFfile"] = sUniqueFileName.ToString();//session variable
System.IO.File.Delete(sFilePath+Session["PDFfile"].ToString());//Session_End Global.asax
<sessionState timeout="5"></sessionState>//web.config, altered to 5 minutes for testing

 


Wednesday, May 25, 2011 10:02 AM ✅Answered

Ok 

Lets confirm if the Session_End event is actually raised.

 

Set your Session Timeout to 2 minutes

Put a break point on the first statement of Session_End method.

 

Wait for 2 minutes

Dont close the browser at all between these times

 

Check if the breakpoint is infact hit.

Let me know the result.


Wednesday, May 25, 2011 10:22 AM ✅Answered

The error was the string sFilePath, my fault I should of realised that you can't put just server.mappath, you have to put:

string sFilePath = System.Web.Hosting.HostingEnvironment.MapPath("~/pdfs/");

Thanks for all your help!


Friday, May 27, 2011 4:11 AM ✅Answered

Ok for anyone that needs a solution to deleting an attachment after sending, here it is:

 

 

try
{ 
SmtpClient client = new SmtpClient(sHost, iPort);
            using (MailMessage message = new MailMessage())
            {
                message.From = new MailAddress(sFrom, sFromAlias);
                message.To.Add(new MailAddress(sEmailTo));
                message.Subject = sSubject.ToString();
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                message.Body = sBody.ToString();
                message.BodyEncoding = System.Text.Encoding.UTF8;

                Attachment oAttach = new Attachment(sAttachment);
                message.Attachments.Add(oAttach);
                
                message.IsBodyHtml = true;
                message.Priority = MailPriority.High;
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential(sFrom, sPassword);
                client.Send(message);

                message.Attachments.Clear();

                message.Dispose();
                oAttach.Dispose();
            }
            if (File.Exists(sAttachment)) File.Delete(sAttachment);

            Response.Write(File.Exists(sAttachment));
        }
        catch(Exception ex)
        {
            Message.Text = "Error: " + ex.ToString();
        }

 

The key is to use 'using' and dispose method and making your attachment a type. Otherwise it just returns errors saying it is being used by another process.

You can include 'using' or leave it out both ways work, I'm not sure what the benefit is of either?


Wednesday, May 25, 2011 6:03 AM

If you want a continously running program, then you will have to create  a Windows Service.

 

Once started it will not have any user interaction.


Wednesday, May 25, 2011 6:25 AM

What if you only have access to your site folder and cannot install the exe file?


Wednesday, May 25, 2011 6:53 AM

I'll give the scenario, and maybe someone can suggest alternatives:

Simple CMS

  • User logs in
  • Fills Form
  • Uploads Images
  • Create PDF (now located on server)
  • PDF emailed out
  • Script runs: deletes anything older than 1hour

Problem is that this 1 file could there for quite a while until someone else fills in the form again, so I could potentially have this sitting on the server for some time which isn't ideal.

I was thinking that I could run the script everytime someone logs into the CMS at the log in screen.

Do you think that this would be advisable?

 


Wednesday, May 25, 2011 7:20 AM

yes this could be the only scenario.

 

Asp.net application will only perform any action upon request by the Client. You can perform the action as soon as a user logs in.


Wednesday, May 25, 2011 7:36 AM

Yes this also possible.....

You can write a script at the time of login to check older file which is from 1 hours. but in this case.... if suppose in 1 minute in your site 100 users loged in then that all time that script runs, so I suggest make one flag that maintain last run time so if that time would be more then or equal to 1 hour then only that delete process runs. That is benifit in your application performance.


Wednesday, May 25, 2011 7:42 AM

Yes this also possible.....

You can write a script at the time of login to check older file which is from 1 hours. but in this case.... if suppose in 1 minute in your site 100 users loged in then that all time that script runs, so I suggest make one flag that maintain last run time so if that time would be more then or equal to 1 hour then only that delete process runs. That is benifit in your application performance.

 

I like that idea!

How would I implement this?

Here is my small script:

    protected void DeleteAllFromFolder(string sFileName)
    {
        DirectoryInfo d = new DirectoryInfo(Server.MapPath(sFileName));
        foreach (FileInfo f in d.GetFiles())
        {
            if (f.CreationTime.AddHours(1) < DateTime.Now)
                File.Delete(f.FullName);
        }
    }

Sorry I have limited c# knowledge!

 


Wednesday, May 25, 2011 8:47 AM

Then start a thread make it go to sleep for one hour and then wake it up
This thread will delete the files and then make it go to sleep again

 


Wednesday, May 25, 2011 9:25 AM

Where are you sessions stored. InProc or Sql server?

 

Also , I suggest you to keep your application running. I think you might have closed the application.


Wednesday, May 25, 2011 9:49 AM

As far as I know the sessions are stored in the Application not sql.

I have kept the application running but it still doesn't seem to delete the file.

I have also place an if statement in the global.asax file:

        string sFilePath = Server.MapPath("~/pdfs/");
        if (Session["PDFfile"] != null)
        {
            System.IO.File.Delete(sFilePath + Session["PDFfile"].ToString());
        }

Any other suggestions?


Wednesday, May 25, 2011 9:57 AM

I also tried:

            string sSpdfFile = sUniqueFileName.ToString();
            Session.Add("PDFfile",sSpdfFile);

But that didn't work either?

 


Wednesday, May 25, 2011 10:09 AM

Yes it did hit the breakpoint but never went through the session_end code it went to the application_error but never gave me any indication to what was wrong?


Wednesday, May 25, 2011 10:11 AM

That means the Session_End method is getting executed. There is some line in the code that is generating the error.

 

Execute line by line after you hit the breakpoint and see what the error is.

 

Also, you can try to put the code in this method in try catch block and find out what exactly the error is.


Wednesday, May 25, 2011 10:23 AM

Please mark the posts as answers if they helped you.


Wednesday, May 25, 2011 10:35 AM

I have :)


Wednesday, May 25, 2011 4:42 PM

What if the user logs out of the system is the session then abandoned? This now seems likely. Would a possiblity be to put my delete all from folders script in the Application_End of my global.asax file as a backup.

So when the user does log out before the 60minute window the application_end will check through the folder and delete anything that is older than 1 hour, if the user sticks around for longer than 60minutes then there isn't a problem, but I can't see them doing that though.

Any help would be appreciated!


Thursday, May 26, 2011 8:59 AM

Yes you are right.

As soon as the user logs out, the Session_End event will get executed and the file shoudl be deleted.

Application_End will exeute only when the application is being shut down. No matter how many users login and logout between this time. I dont think that is the perfect place for your purpose.