简体   繁体   中英

Get parameters from text file c#

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"

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);
    }

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);

似乎您正在尝试解析一个ini文件,该文件已经有一些可用的选项

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM