Member-only story
Automate Email Alerts for Critical Errors in Log Files using C#— Code, Execute, and Automate
Introduction:
Sending email alerts when an error occurs in your application or system is a crucial step to ensure that your team is notified of any issues as soon as possible. In this article, we’ll discuss a C# code that sends email alerts based on specific errors found in log files.

Code Explanation:
The code is a console application that uses several system libraries to function properly. These libraries include System, System.Text, System.Collections.Generic, System.Threading.Tasks, System.IO, System.Linq, System.Net.Mail, and System.Net.
The Main method is the entry point for the application. It begins with a try-catch block to catch any exceptions that may occur during the program’s execution.
using System;
namespace SendEmailAlerts
{
class Program
{
static void Main(string[] args)
{
try
{
// Code goes here
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
The rootPath
variable is set to the path of the directory where the system or application log files are located.
string rootPath = @"D:\Logs";
The files
variable is set to an array of file paths for all files in the directory that match the search pattern (".log") and fetches the most recent log file. This code first creates a new DirectoryInfo
object with the rootPath
. It then calls the GetFiles
method to get all files in the directory that match the search pattern (".log") and all subdirectories. The OrderByDescending
method is used to sort the files in descending order by creation time. Finally, the FirstOrDefault
method is called to select the first file in the sorted list, which is the most recent log file.
var files = new DirectoryInfo(rootPath)
.GetFiles("*.log*", SearchOption.AllDirectories)
.OrderByDescending(x => x.CreationTime)
.FirstOrDefault();
The errorList
variable is initialized as an empty list of strings.
List<string> errorList = new List<string>();