Export Logs - C# (Text)

Export Logs - C# (Text)

Pritom Purkayasta's photo
Pritom Purkayasta
ยทJun 6, 2021ยท

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

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.


and now tackling the string option.


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