Export Logs - C# (CSV)

Export Logs - C# (CSV)

ยท

2 min read

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

Sometimes we have to audit some of our data for proper validation. In that case, we will have a dedicated class to generate this kind of log. If you are interested in built-in value types such as string or string builder objects consider looking at this article .

So let's create the scenario first. Let's just assume our model.

class DummyModels
{
    public string Id { get; set; }
    public string Name { get; set; }
}

and to create this we have to seed our data.


List<DummyModels> dummyModels = new List<DummyModels> {
            new DummyModels {
                Id = Guid.NewGuid().ToString(),
                Name = Guid.NewGuid().ToString()
            }
        };

You may already have a data seeder or some other way to bucket up the list So let's go straight to our main function.

So In order to write the data to our disk, we need a third-party open-source library called CsvHelper to help us.

To Generate the files to our disk we need to define e delimiter for the file to properly do the spacing and it will help us to import it in the future. Using CsvHelper we have to define the configuration first. We can define a lot of configuration around the road but that will do for now.

public static void ToLocalDisk(IEnumerable<T> models, string fileName) 
{
 CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
 {
    Delimiter = "|"
 };
}

Now we have to create a stream-writer that will write our file to the disk. In order to write to a stream writer, we have to write our file to CsvWriter that will write to the stream writer.

using StreamWriter streamWriter = new StreamWriter(_location + "/" + fileName, false, Encoding.UTF8);
using CsvWriter csvWriter = new CsvWriter(streamWriter, csvConfiguration);
csvWriter.WriteRecords(models);

For better reusability, we are going to make this generic. That's the whole code. And that should do the magic.

public class Exporter<T> where T: class

    private readonly static string _location = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)?.Replace("\\", "/");
    public static void ToLocalDisk(IEnumerable<T> models, string fileName)
    {
        CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            Delimiter = "|"
        };

        using StreamWriter streamWriter = new StreamWriter(_location + "/" + fileName, false, Encoding.UTF8);
        using CsvWriter csvWriter = new CsvWriter(streamWriter, csvConfiguration);
        csvWriter.WriteRecords(models);
        }
    }
`

If you want to export this list of models in Excel without using any third-party package, you are in luck. Check this blog post.

Happy Coding ๐Ÿ’ฏ