views:

1059

answers:

7

Hey all,

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.

+3  A: 

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

astander
Can you reccomend any good sites to begin learning XML for C#? I did consider this, but I couldn't find any useful sites about it.
baeltazor
+1 As a rule of thumb I'd use XML if the files must be accessible via other apps, and binary serialization otherwise.
Mark Seemann
Aggreed, xml just makes it human readable/editable
astander
Generally you don't even have to know how to read or write XML in .NET - you just pass your object, or list of objects, to an XMLWriter and it will serialize it for you (if possible ie containing only serializable types). To read it back, you pass the file path to an XMLReader and get back an object you can cast to the original. It's almost a bit too easy to use for configuration. Also, use %appdata% (http://stackoverflow.com/questions/867485 ) to store it on a Windows system - do not store it in the application directory ^^
Oskar Duveborn
have a look at these siteshttp://www.developer.com/net/csharp/article.php/3489611/Manipulate-XML-File-Data-Using-C.htmhttp://www.codeproject.com/KB/cpp/XMLReadWrite.aspx
astander
A: 

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.

Andrew Keith
Judging by the sample code for CSV files I've found online, it is much different than writing plain old text files, and there also seems to be alot more to it.
baeltazor
A CSV file is just a plain old text file, hence the name comma separated value file.
Andrew Keith
Yes, it is a "plain" text file, but the logic behind generating a "coorect" csv is slightly more comple. excel has it pretty well covered in cell formatting, and values that contain the "split" delimitter. So no, it is not as easy as just writing your own text file.
astander
Thank you astander.
baeltazor
+2  A: 

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.

Jonas Elfström
A: 

If you want to use CSV, don't USE COMMAS use a pipe or some other uncommon character!

I've lost track of the amount of time I've wasted editing exports from databases, excel etc I've been given before importing it somewhere else to remove the commas because people routinely use them in every day language from addresses to comments.

L2Type
Embedded commas must be contained within quotes, else it isn't CSV.
dalle
I am not embedding commas anywhere!
baeltazor
In your sample you put "This is LinkLabel's text", without the quotes, I assume this could be any text, including at some point text with comments. Not too sure why I got down voted for pointing out that using commas to separate it up could cause you problems here.
L2Type
i'm sorry you got down-voted, but that wasn't me who down-voted you... +1
baeltazor
+2  A: 

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.

Marc Gravell
A: 

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.
Guffa
Maybe not a standard but there is RFC 4180 http://tools.ietf.org/html/rfc4180 http://en.wikipedia.org/wiki/Comma-separated_values but I do agree that there's often problems with CSVs.
Jonas Elfström
@Jonas: That's a nice overview, it would have been handy a while back when I wrote a CSV parser, but then it wasn't published yet... Note that MS Excel produces CSV files that are broken accoring to those definitions (i.e. jagged lines).
Guffa
+2  A: 

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]
Denk Hanners