0

I have a text file that is formatted like so...

[Dimensions]
Height=100
Width=200
Depth=1000

I am trying to write a method that takes the parameter name such as "Height" with the text and returns the value of the parameter but it is currently not working

public int getParameter(data, param) {
        var start = data.IndexOf(param);
        var end = data.IndexOf('\r\n', start);
        return data.Substring(start + param.length + 1, end);
    }

But it always returns partial text on the next line such as

"100\r\nWid"

Stacker-flow
  • 1,251
  • 3
  • 19
  • 39

5 Answers5

2

I'd probably use a regular expression for that:

public int getParameter(string data, string param) {
        var expr = "^" + param + @"=(\d+)\r?$";
        var match = Regex.Match(data, expr, 
                                  RegexOptions.Multiline | RegexOptions.IgnoreCase);
         // NB - can remove the option to IgnoreCase if desired
        return match == null || !match.Success ? default(int) : int.Parse(match.Groups[1].Value);
    }
James S
  • 3,558
  • 16
  • 25
0

You are passing wrong value to second parameter for Substring.It's the lenght, not the end index, so it should be:

var startIndex = start + param.length + 1;

return data.Substring(startIndex, end - startIndex);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

Looks like you're trying to parse an ini file, for which there are already some options avaiable.

Community
  • 1
  • 1
Carra
  • 17,808
  • 7
  • 62
  • 75
0

This looks pretty similar to TOML, you might want to do minor changes and use the TOML.NET Package.

I didn't test it, but used TOML in a go project and it worked quite well. Takes some effort from yourself.

krizz
  • 412
  • 3
  • 5
0

That file follows the ini format, so I'll recommend using ini-parser for reading it: https://github.com/rickyah/ini-parser

Is as simple as:

   var parser = new FileIniDataParser();
   IniData parsedData = parser.LoadFile("config.ini");
   int height = Int32.parse(parsedData["Height"])

Disclaimer, I'm the author of the library

Ricardo Amores
  • 4,597
  • 1
  • 31
  • 45