How to include to build at .NET parsed csv?

Viewed 49

I have translation file with a 13000 of lines. Now at starting the app I read it from manifest resource

var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("filename.csv")

and parse them via CsvParser.

It's slow operation (takes ~2seconds). I am looking for ways to pre-parse it at build time, so I can access it like that:

var lines = SomeCode.ParsedLines;

Any recommendations how can I do that? I could just write a gigantic .cs file like

"ParsedLines= new string[,]{{"title1","title2"},{"word1","word2"}}"

but the problem is that the .csv file is frequently modified. My best guess is to create a code generator that will create this .cs file at each build, but I am wondering if there are any better approaches.

1 Answers

This is one of the textbook use cases for source generators. Using a source generator you can parse your csv file at the build time and generate source for a class which will be compiled in the next steps.

Another useful article - introducing C# source generators. Also potentially you can find useful - source generators cookbook, my sandbox source generator project.

Also you can try looking into processing the csv file manually without CsvHelper (since you control it and you are sure about formatting, escaping, etc.) via using standard File.ReadLines or via System.Pipelines to improve performance.

Related