Is there such thing as a CSV Serializer? (similar to XmlSerializer)

前端 未结 3 854
-上瘾入骨i
-上瘾入骨i 2021-01-17 10:18

I am toying around with serializing and deserializing CSV files and I am wondering if there is an existing library, similar in concept to the XmlSerializer, which can declar

相关标签:
3条回答
  • 2021-01-17 10:41

    You should take a look into FileHelpers Library.

    Some sample code from their site:

    using FileHelpers; 
    
    // First declare the record class 
    [DelimitedRecord(",")] 
    public class SampleType 
    { 
        public string Field1; 
        public int    Field2; 
    } 
    
    public void WriteExample() 
    { 
        FileHelperEngine engine = new FileHelperEngine(typeof(SampleType)); 
    
        SampleType[] records = new SampleType[1]; 
    
        records[0] = new SampleType(); 
        records[0].Field1 = "Hello World"; 
        records[0].Field2 = 12; 
    
        engine.WriteFile("destination.txt", records); 
    
        // Now the file contains the created record in this format: 
        //  
        // Hello World,12 
    } 
    
    0 讨论(0)
  • 2021-01-17 10:42

    I've used this project (CsvHelper) in the past, and it works similar to the build in .NET serializer classes in the sense that you use attributes to craft the input/output.

    There's really no need to roll your own, since there are tons out there. If you do end up rolling your own, feel free to post it. Most users, when answering a question with something they've written themselves (or are affiliated in some way) usually give a disclaimer saying so as a courtesy.

    0 讨论(0)
  • 2021-01-17 11:00

    I would highly recommend servicestack.text for this purpose. Avialable on nuget:

    Install-package servicestack.text
    

    It suports serialization to many data formats and unlike the built in XmlSerializer, you don't need to decorate all your properties with attributes. Here's an example to serialize to CSV.

    using ServiceStack.Text;
    ...
    
    var csv = CsvSerializer.SerializeToCsv(new[]{
        new Dog () {
        Bark = "Woof!",
        Male = true,
        Size = 10
    }});
    
    0 讨论(0)
提交回复
热议问题