Privacy Info

Tuesday, August 24, 2021

File Cleaner - Console Application


It is a ASP.NET console application which will remove your old files as per the configurations. It would be helpful to remove old log files in your application which will consume space.

1. Create a console application in Visual Studio.

2. Install the log4net from Nugget Package Manager for logging purpose.

3. Create log4net.config file and add below code in that file also set properties of file Copy if Newer.

Code

<log4net>
	<root>
		<level value="ALL" />
		<appender-ref ref="console" />
		<appender-ref ref="file" />
	</root>
	<appender name="console" type="log4net.Appender.ConsoleAppender">
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date %level - %message%newline" />
		</layout>
	</appender>
	<appender name="file" type="log4net.Appender.RollingFileAppender">
		<file value="C:\Users\Projects\FileCleaner\FileCleaner\bin\Debug\Logs\FileCleaner_" />
		<appendToFile value="true" />
		<rollingStyle value="Date" />
		<maxSizeRollBackups value="5" />
		<datePattern value="yyyyMMdd'.txt'" />
		<staticLogFileName value="false" />
		<maximumFileSize value="10MB" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date %level - %message%newline" />
		</layout>
	</appender>
</log4net>

4. Add Reference of log4net in AssemblyInfo.cs file

Code 

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FileCleaner")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FileCleaner")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//log4net Assembly Added
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

5. In Program.cs file add the below code

Code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileCleaner
{
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            try
            {
                log.Info(String.Format("****************************Run Started***********************************"));

                List<FilesFolderDetails> filesFolderDetails = FilesFolderDetails.GetFilesFolderDetails();
                
                
                foreach (var filesFolderDetail in filesFolderDetails)
                {
                    try
                    {

                        string folderName = filesFolderDetail.FolderLocation;
                        int oldFilesInDays = filesFolderDetail.OldfilesInDays;
                        string[] fileExtensions = filesFolderDetail.FileExtensions;

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

                        foreach (string file in files)
                        {
                            try
                            {
                                FileInfo fileInfo = new FileInfo(file);
                                if (fileInfo.LastWriteTime < DateTime.Now.AddDays(oldFilesInDays) || fileInfo.LastAccessTime < DateTime.Now.AddDays(oldFilesInDays))
                                {
                                    if (fileExtensions == null || fileExtensions.Length <= 0)
                                    {
										//File Delete
                                        fileInfo.Delete();
                                        log.Info(String.Format("{0} file deleted sucessfully", fileInfo.FullName));

                                    }
                                    else if (fileExtensions != null || fileExtensions.Length > 0)
                                    {
                                        foreach (var fileExtension in fileExtensions)
                                        {

                                            if (fileExtension.Equals(fileInfo.Extension) || String.IsNullOrEmpty(fileExtension))
                                            {
                                                //File Delete
												fileInfo.Delete();
                                                log.Info(String.Format("{0} file deleted sucessfully", fileInfo.FullName));
                                            }

                                        }
                                    }
                                    else
                                    {
                                        //File Skipped
                                        log.Info(String.Format("{0} file skipped", fileInfo.FullName));

                                    }

                                }
                                else 
                                {
                                    //File Skipped
                                    log.Info(String.Format("{0} file skipped", fileInfo.FullName));
                                }

                            }
                            catch (Exception ex)
                            {
                                log.Error(String.Format("Exception {0}", ex));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(String.Format("Exception {0}", ex));
                    }

                }

                log.Info(String.Format("****************************Run Completed*********************************"));

            }
            catch (Exception ex)
            {
                log.Error(String.Format("Exception {0}", ex));
            }
          
        }
    }
}

6. Create FileFolderDetails.cs file and add  below code 

Code

using System;
using System.Collections.Generic;

namespace FileCleaner
{
    class FilesFolderDetails
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public string FolderLocation { get; set; }
        public int OldfilesInDays { get; set; }
        public string[] FileExtensions { get; set; }

        public static List<FilesFolderDetails> GetFilesFolderDetails()
        {
            List<FilesFolderDetails> filesFolderDetails = new List<FilesFolderDetails>();

            try
            {
                string UrlsFilePath = System.Configuration.ConfigurationManager.AppSettings["FileLocationsPath"].ToString();

                //Getting FilesFolderDetails from Json File
                string json = System.IO.File.ReadAllText(UrlsFilePath);
                filesFolderDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<List<FilesFolderDetails>>(json);

            }
            catch (Exception ex)
            {
                log.Error(String.Format("{0}  Exception {1}", DateTime.Now, ex));
            }

            return filesFolderDetails;
        }
    }
}

7. Create file with FolderLocation.json file and specify the folder locations as shown below and set properties of file Copy if Newer.

Code

[
  {
    "FolderLocation": "C:\\User\\Projects\\FileCleaner\\FileCleaner\\bin\\Debug\\Test",
    "OldfilesInDays": "-5",
    "FileExtensions": []
  },
  {
    "FolderLocation": "C:\\User\\Projects\\FileCleaner\\FileCleaner\\bin\\Debug\\Test2",
    "OldfilesInDays": "-5",
    "FileExtensions": [ ".log", ".txt" ]
  }
]

8.  In App.config file add code for the FolderLocation.json file

Code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
	<appSettings>
		<add key="FileLocationsPath" value="C:\User\Projects\FileCleaner\FileCleaner\FoldersLocation.json"/>
	</appSettings>
</configuration>

9. Apply the settings as per the requirement and run the application. It will remove all the files which will not satisfy the condition. 


Sitecore PowerShell Script - Remove item from Workflow

We came across scenario where we need to remove multiple items from workflow. If items would be less then there would not be any issue but i...