0

I have a text file (currently in CSV format) as follows:

RACE,"race_human"
GENDER,"male"
AGE,30
ALIGNMENT,"align_lawful_good"
DEITY,"Old Faith"

However, I want to interpret the text file as if it were a list of variables. I.e.:

var RACE:string = "race_human";

Is there an easy way to do this, for instance reformatting the text file in the native language used by the program code?

posfan12
  • 2,541
  • 8
  • 35
  • 57

1 Answers1

2

You could split each line on the comma then place each item into a dictionary (provided the keys are unique). Use Dictionary.TryGetValue if there's a chance that a key does not exist.

string[] input = File.ReadAllLines(CSV-File-Here);
var dict = input.Select(s => s.Split(','))
                .ToDictionary(s => s[0], s => s[1]);

// show alignment
string alignment = dict["ALIGNMENT"];
Console.WriteLine(alignment);

// show all values
foreach (var key in dict.Keys)
{
    Console.WriteLine("{0}: {1}", key, dict[key]);
}

EDIT: you might be interested in FileHelpers to work with CSV files.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • Cool. I am trying to use this (http://www.codeproject.com/KB/database/CsvReader.aspx) library at CodeProject, and am waiting to see if I get a response. – posfan12 Jan 28 '11 at 07:05
  • I'm having trouble figuring out the syntax for a JScript .NET dictionary object. I have "private var myDictionary: Dictionary;", but the compiler complains that it's missing a semicolon and that the Dictionary object is not declared. – posfan12 Jan 28 '11 at 07:48
  • @posfan12 I'm not familiar with JScript.NET, you'll have to look around for examples. Also, is this current question for C# or JScript.NET? If it's the latter you might want to update your question to specify and add an appropriate tag for it. – Ahmad Mageed Jan 28 '11 at 14:41
  • It's for JScript .NET. Updated. – posfan12 Jan 28 '11 at 23:11
  • Also, I know JScript does have a native dictionary-like object format, but I'm not sure if there are disadvantages to using it instead of the .NET-specific construct. I.e., what if someone wants to extend my script using another .NET language? Will ask a separate question I guess. – posfan12 Jan 28 '11 at 23:17