Engineering Gratitude πŸŽ‰πŸ‘

Engineering Gratitude πŸŽ‰πŸ‘

Export Logs - From String or StringBuilder

Export Logs - From String or StringBuilder

Subscribe to my newsletter and never miss my upcoming articles

In any console/web application, there will be some log generation to better track what is happening in our application.

In C#, you can easily generate those logs by simple 2 or 3 lines of code only.

For exporting string and StringBuilder type values we are going to make 2 overloads called ToLocalDisk().

Let's first tackle the StringBuilder option.

image.png

and now tackling the string option.

image.png

so the overall code looks like this.

In this code _location is just set to the bin folder (execution folder). You can give whatever location you want.

public class Exporter
{
    private readonly static string _location = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)?.Replace("\\", "/");
    public static void ToLocalDisk(StringBuilder models, string fileName)
    {
       File.WriteAllText(_location + "/" + fileName, models.ToString());
    }
    public static void ToLocalDisk(List<string> models, string fileName)
    {
        StringBuilder sb = new StringBuilder();
        models.ForEach(i => sb.AppendLine(i));
        File.WriteAllText(_location + "/" + fileName, sb.ToString());
    }
}

Happy Coding πŸ’―πŸ’―

Β 
Share this