Create a configuration ". TXT" file

Asked

Viewed 76 times

1

My problem is this, I need to make a configurable file to integrate to my project, follow its format currently:

PRINTER = 127.0.0.12
PRINTER_PORT = 9100

I’d like to format it for this style:

[PRINTER]
PRINTER = 127.0.0.12
PRINTER_PORT = 9100

Currently I am using the Dictionary method to obtain the data, do you have a better option? Since if you use brackets to highlight the file my function does not read them. Function:

var dic = File.ReadAllLines("config.txt")
          .Select(l => l.Split(new[] { '=' }))
          .ToDictionary(s => s[0].Trim(), s => s[1].Trim());
                VariaveisGlobais.DEFAULT_PRINTER = dic["PRINTER"];
                VariaveisGlobais.DEFAULT_PRINTER_PORT = dic["PRINTER_PORT"];

1 answer

2


Whether the format is similar to that of the .ini can try something ready, search in nuget, example: https://www.nuget.org/packages/ini-parser/, to install:

PM> Install-Package ini-parser -Version 2.5.2

The advantage of this specific lib is that it does not depend on Windowsapi, which is advantageous for porting your code to other environments.

Example of use:

Add the classes:

using IniParser;
using IniParser.Model;

To upload the file:

var parser = new FileIniDataParser();
IniData data = parser.ReadFile("Configuration.ini");

To read as string:

 string useFullScreenStr = data["UI"]["fullscreen"];

In the example if the value is "true" you can do the parse like this:

bool useFullScreen = bool.Parse(useFullScreenStr);
  • I didn’t even know I had something ready for a parser, it really helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.