jay_t55
jay_t55

Reputation: 11652

Comma Separated Value Files (Read/Write) - C#

I've been very interested in CSV files for a few years now, but I never needed to use them until now, so I'm pretty new to this.

I have an application that stores information about Controls that were created by the user at run-time. I plan on using CSV files to store this information which will be extracted at a later date by a user when they open the file into my program.

These CSV files will have the following structure. Let's say, for example, a user creates a LinkLabel, assigns some text to it, and then creates a Label and assigns some text to that, too. The output file (CSV file) will look like this:

CSVFile.csv


LinkLabel,This is LinkLabel's text,170,40
Label,This is Label's text,170,50

Explanation:


Control,Text,LocationX,LocationY
Control,Text,LocationX,LocationY

..So, as you can see, the information will always be the same. Control, Text, LocationX, LocationY...

Can anybody point me to any good, easy to understand resources where I can learn how to write such a file? And then extract that information aswell?

Thanks, Jason.

Upvotes: 3

Views: 2520

Answers (6)

Denk Hanners
Denk Hanners

Reputation: 51

As a much lighter weight alternative to XML, JSON provides you with all that you seem to be looking for. JSON is just a way for serialising your objects to strings suitable for writing to a file, for later retrieval.

There is an active community of JSON users that use the JSONSharp module jsonsharp overview.

For a discussion about why XML (may) be bad for your health there is an extremely helpful post here: xml is bad for humans

returning to your question about CSV files, C# indeed does not include any solutions for writing and reading csv files, and as others have mentioned, your first port of call should be one of the many libraries that have sprung up to fill the void.

This is what your structure might look like in JSON:

["LinkLabel","This is LinkLabel's text",170,40]

Upvotes: 2

Guffa
Guffa

Reputation: 700322

There is no defined standard for how a CSV file should work, so using them is problematic. I would recommed using XML instead, as there is a clear standard that you can refer to.

Some things that makes the CSV format problematic:

  • Values can contain line breaks, so you can't read the file line by line.
  • Some files are not comma separated at all, but semicolon separated.
  • Some files have jagged line lengths, i.e. lines with different number of items.
  • As there are no rules for how values should be quoted and escaped, it's tricky to write a parser that can handle different way that it's solved.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062770

I wonder whether xaml wouldn't do most of what you want for free? But if you want bespoke data, I too would suggest that csv has had its day, especially when the data gets complex. For a complete xml example (written for space, so ignore the formatting):

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public enum ControlType {
    Label, LinkLabel
}
[XmlRoot("controls")]
public class ControlWrapper {
    [XmlElement("control")] public List<ControlDto> Controls { get; set; }
    public ControlWrapper() {
        Controls = new List<ControlDto>();
    }
}
public class ControlDto {
    [XmlAttribute("type")] public ControlType Type { get; set; }
    [XmlAttribute("caption")] public string Caption { get; set; }
    [XmlAttribute("x")] public int LocationX { get; set; }
    [XmlAttribute("y")] public int LocationY { get; set; }
}
static class Program {
    static void Main() {
        var model = new ControlWrapper {
            Controls = {
                new ControlDto {
                    Type = ControlType.LinkLabel,
                    Caption = "This is LinkLabel's text",
                    LocationX = 170, LocationY = 40
                }, new  ControlDto {
                    Type = ControlType.Label,
                    Caption = "This is Label's text",
                    LocationX = 170, LocationY = 50
                }
            }
        };
        var ser = new XmlSerializer(typeof(ControlWrapper));
        ser.Serialize(Console.Out, model);
    }
}

This way you mainly deal with the object model, not the serialization. Indeed, it would be trivial to modify the above to use DataContractSerializer (for WCF), protobuf-net (portable binary), etc.

Upvotes: 2

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31428

I use the excellent and free FileHelpers library for handling CSV-files. That said I'm not so sure that you really should use a CSV-file for what you are trying to do.

Here you can see how others have implemented a similar feature.

Upvotes: 3

Andrew Keith
Andrew Keith

Reputation: 7563

Your question basically is about how to write into a file.

Google and read some samples.

Basically you are looking at the creating an instance of the FileStream class and writing to disk.

I would post an example, but its best you study a bit first, then repost a more specific question.

Writing to a CSV is essentially just writing to a text file.

Upvotes: -2

Adriaan Stander
Adriaan Stander

Reputation: 166396

I would avoid a csv file, and maybe rather use a xml file. This will give you a lot more flexability, and supported readers.

Upvotes: 3

Related Questions