June 12, 2017

Open New Window from Server Side in ASP.Net using C#

Here Is the question I received from one of my colleagues, how to open new page from server side in a new window. There could be two possible ways to get it work.

  • First option is to add javascript code to the button's OnClientClick handler. But this handler should be attached before the control is rendered, let's say in button's OnPreRender event.

    protected void MyButton_OnPreRender(object sender, EventArgs e)
    {
        string newPageUrl = "NewPage.aspx";
        MyButton.OnClientClick = "window.open('" + newPageUrl + "'); return false;";
    }
    

    This technique would not let the request post back to the server, so it could save this round-trip.

  • Second option could be use of Response.Write() method on regular button click event.

       Response.Write("<script>window.open('http://www.google.com.hk/','_blank');</script>"); 
    

    This would send a post back to the server, but the advantage to this method could be that it will allow you write code on button click you may want to execute before opening a new window.

June 5, 2017

C# - Delete files older than N number of Days/Months

In this post, I will share C# code to delete files from specific directory, with the condition that only files which are older than N number of Days or Month or any other time unit. Why I come to this code because recently we faced this problem because of not deleting the older files.

I was working on a small utility program to automate repeated tasks, one of which is to take daily backups for my project's database. This was done before, but after some time we faced this problem because we were running out of space, it happens for the reason that we have lot of backup files generated and no one is going to delete older files which are of no-use. The best solution come to my mind is to modify the program code to delete older files by it-self.

Here is the C# code for this task.

string[] files = Directory.GetFiles(directoryPath);

foreach (string file in files)
{
   FileInfo fi = new FileInfo(file);
   
   if (fi.LastAccessTime < DateTime.Now.AddMonths(-1))
   {
       fi.Delete();   
   }
}

Obviously you can change DateTime.Now.AddMonths method to AddDays, AddHours or other units according to your requirements.