CsvSourceGenerator is a .NET source generator for generating CSV serialization code for your classes and records. This project leverages C# Source Generators to automatically create boilerplate code, making it easier to handle CSV serialization.
These instructions will help you set up the CsvSourceGenerator in your .NET project.
- .NET SDK 5.0 or higher
As of now, no NuGet packages are available for CsvSourceGenerator. You need to clone the repository and include the project in your solution.
-
Clone the repository:
git clone /~https://github.com/Sadra-jl/CsvSourceGenerator.git
-
Add the project to your solution:
In your solution directory, add the CsvSourceGenerator project:
dotnet sln add CsvSourceGenerator/CsvSourceGenerator.csproj
-
Reference the CsvSourceGenerator project:
In your project file (
.csproj
), add a project reference withOutputItemType="Analyzer"
(otherwise it will not work):<ProjectReference Include="..\CsvSourceGenerator\CsvSourceGenerator.csproj" OutputItemType="Analyzer" />
-
Build your project:
You can build your project to make sure that the source generator is correctly integrated and that the CSV serialization code is generated.
dotnet build
If you prefer a NuGet package for easier integration, feel free to open an issue or contact me directly, and I will create one.
-
Apply the
CsvSerializableAttribute
: Apply theCsvSerializableAttribute
to the classes or records you want to be CSV serializable. The source generator will also generate theICsvSerializable
interface, which these classes or records will implement. then make the type as partialusing PaleLotus.CsvSourceGenerator; [CsvSerializable] public partial record MyRecord(int Id, string Name); [CsvSerializable] public partial class MyClass { public int Id { get; set; } public string Name { get; set; } }
-
Build Your Project: When you build your project, the source generator will automatically implement the
ICsvSerializable
interface and CSV serialization code for the marked classes and records.
Here’s an example of a generated CSV serialization class:
namespace MyNamespace
{
public partial class MyClass : PaleLotus.CsvSourceGenerator.ICsvSerializable
{
public string ToCsv() => $"{Id},{Name}";
public string GetCsvHeader() => $"Id,Name";
}
}
namespace MyNamespace
{
public partial record MyRecord : PaleLotus.CsvSourceGenerator.ICsvSerializable
{
public string ToCsv() => $"{Id},{Name}";
public string GetCsvHeader() => $"Id,Name";
}
}
We welcome contributions to enhance CsvSourceGenerator! Here's how you can help:
- Fork the repository.
- Create a feature branch (
git checkout -b feature/AmazingFeature
). - Commit your changes (
git commit -m 'Add some AmazingFeature'
). - Push to the branch (
git push origin feature/AmazingFeature
). - Open a Pull Request.
This project is licensed under the Apache License Version 2.0. See the LICENSE file for more details.
- Microsoft for the Roslyn API.
- The .NET community for their valuable contributions and feedback.