This method purge all files in current execution path, which are older than 10 days.
This method usage the another user defined method to get the execution path. This method delete all the files from the execution path directory which are older than the given days. you can change the number of days and also hard code the execution path.
Please let us know if you face any problem in implementing the given scenario.
Please note that this method will delete only *.log files from the given directory, you can change the file type from the code.
- /// <summary>
- /// This method purge all files in current execution path, which are older than DaysToKeepHistory.
- /// </summary>
- public static void PurgeOldFiles()
- {
- int intNoOfDays;
- DateTime TodaysDate;
- DirectoryInfo dir = null;
- FileInfo[] Files = null;
- try
- {
- intNoOfDays = 10;
- TodaysDate = DateTime.Now.Date;
- dir = new DirectoryInfo(GetExecutionPath());
- Files = dir.GetFiles("*.log");
- foreach (FileInfo LogF in Files)
- {
- if (DateTime.Compare(TodaysDate, LogF.LastWriteTime.AddDays(intNoOfDays)) >= 0)
- {
- LogF.Delete();
- }
- }
- }
- catch (Exception ex)
- {
- // Unable to purge Files : Message : ex.Message
- }
- finally
- {
- if (dir != null)
- {
- dir = null;
- }
- if (Files != null)
- {
- Files = null;
- }
- }
- }
- /// <summary>
- /// This method will retunrns the execution path of our application.
- /// This method returns execution path for web application as well as windows service.
- /// </summary>
- /// <returns>Returns <see cref="System.String"/> value.</returns>
- public static string GetExecutionPath()
- {
- string ExecutionPath = "";
- try
- {
- ExecutionPath = System.Web.HttpContext.Current.Server.MapPath("ServiceConfig.xml");
- }
- catch
- {
- }
- if (ExecutionPath == "")
- {
- ExecutionPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
- }
- try
- {
- string strExeName = FileSystem.Dir(ExecutionPath, 0);
- string FilePath = Path.GetFullPath(ExecutionPath.Substring(0, (ExecutionPath.Length - strExeName.Length)));
- return FilePath;
- }
- catch
- {
- throw;
- }
- }
While “ServiceConfig.xml” is a configuration file kept in root of web application and windows application.
0 comments:
Post a Comment