0
votes

I have a text file with conversions called "ConversionsDefault.txt" such as feet to meters, miles to kilometers, etc. in this format:

Miles|Kilometers|1.6093

Feet|Meters|0.3048

I want to read this text file into a rectangular array consisting of the first length option, the second length option, and the multiplier converting the first to the second.

I also have an add button for adding new conversion types such as A|B|50.00; it could be anything with any multiplier. This add button should add the new conversion types along with the default conversion types to a text file called "Conversions.txt".

Any help would be greatly appreciated.

1
This looks pretty straight forward to me. Where did you got stuck? - Einer

1 Answers

0
votes

You can use File.ReadAllLines and some Linq:

var rows = File.ReadAllLines("ConversionsDefault.txt").Select(l => l.Split('|')).ToArray();

Then:

Console.WriteLine(rows[0][0]); // Will output Miles
Console.WriteLine(rows[0][1]); // Will output Kilometers
Console.WriteLine(rows[0][2]); // Will output 1.6093
Console.WriteLine(rows[1][0]); // Will output Feet
Console.WriteLine(rows[1][1]); // Will output Meters
Console.WriteLine(rows[1][2]); // Will output 0.3048

Or you could save the data to a struct:

public struct ConversionDetails
{
    public readonly string Unit1;
    public readonly string Unit2;
    public readonly Decimal Ratio;

    public ConversionDetails(string[] line)
    {
        Unit1 = line[0];
        Unit2 = line[1];
        Ratio = Decimal.Parse(line[2]);
    }
}

var rows = File.ReadAllLines("ConversionsDefault.txt").Select(l => new ConversionDetails(l.Split('|'))).ToArray();