Victor Bjelkholm
Victor Bjelkholm

Reputation: 2216

Get values from textfile with C#

I've got a textfile which contains the following data:

name = Very well sir
age = 23
profile = none
birthday= germany
manufacturer = Me

And I want to get the profile, birthday and manufacturer value but can't seem to get it right. I succeded including the file into my program but there it stops. I just can't figure out how I will clean the textfile up.

Here's my current code: http://sv.paidpaste.com/HrQXbg

Upvotes: 1

Views: 14893

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        var data = File
            .ReadAllLines("test.txt")
            .Select(x => x.Split('='))
            .Where(x => x.Length > 1)
            .ToDictionary(x => x[0].Trim(), x => x[1]);

        Console.WriteLine("profile: {0}", data["profile"]);
        Console.WriteLine("birthday: {0}", data["birthday"]);
        Console.WriteLine("manufacturer: {0}", data["manufacturer"]);
    }
}

Upvotes: 4

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

You need to split into lines first and then split the lines:

StreamReader reader = new StreamReader(filePath);
string line;
while(null != (line=reader.Read())
{
    string[] splitLine = strLines.Split('='); 
    //Code to find specific items based on splitLine[0] - Example
    //TODO: Need a check for splitLine length
    case(splitLine[0].ToLower().Trim())
    {
        case "age": { age = int.Parse(splitLine[1]);
    }
}

reader.Dispose();

This should make a good start for you.

Upvotes: 0

Ed Bayiates
Ed Bayiates

Reputation: 11210

I would suggest instead of using ReadToEnd, reading each line and doing a string.Split('=') and then a string.Trim() on each line text. You should be left with 2 values per line, the first being the key and the second, the value.

For example, in your reading loop:

List<string[]> myList = new List<string[]>();
string[] splits = nextLine.Split('=');
if (splits.Length == 2)
    myList.Add(splits);

Upvotes: 0

Related Questions