Reputation: 135
I searched around and everyone kept saying the best way to handle CSV files in C# is Filehelpers. But I keep looking and I can't find a comprehensive guide as of how to append a csv file. I have this class:
class FlashCard
{
public static string Front { get; private set; }
public static string Back { get; private set; }
public static Difficulty CardDifficulty { get; private set; }
public enum Difficulty
{
easy,
medium,
hard,
very
}
public void Flashcard(string front, string back, Difficulty Difficulty )
{
Front = front;
Back = back;
CardDifficulty = Difficulty;
}
}
And I want to save instances of it inside a CSV file. But how?
Upvotes: 0
Views: 592
Reputation: 11326
To write a CSV file from your class using FileHelpers, map your class to a 'spec' class which describes the CSV file. Something like this.
[DelimitedRecord(",")]
public class FlashCardCsvRow
{
public string Front;
public string Back;
public string CardDifficulty;
}
var flashcards = new List<FlashCard>(); // your class above
// populate flashcards however you like
var csvRows = flashCards.Select(x =>
new FlashCardCsvRow()
{
Front = x.Front,
Back = x.Back,
CardDifficulty = x.CardDifficulty.ToString();
});
var engine = new FileHelperEngine<FlashCardCsvRow>();
engine.WriteFile("Output.Txt", csvRows);
FileHelpers has lots of nice features to help you further. For instance you might want to implement your own enum converter instead of using x.CardDifficulty.ToString()
.
By the way, you'll run into trouble with your static
properties in FlashCard
. I'm not sure you meant to make those properties static.
Upvotes: 0
Reputation: 5668
You have to have already a csv file, then you can easily convert this file to your entities (like FlashCards).
Take a look on quick start http://www.filehelpers.net/quickstart/
First of all you have to mark your class with attribute [DelimitedRecord(",")]
Upvotes: 2