GithubHelp home page GithubHelp logo

salaros / config-parser Goto Github PK

View Code? Open in Web Editor NEW
112.0 2.0 14.0 332 KB

A slim, fully managed C# library for reading/writing .ini, .conf, .cfg etc configuration files.

Home Page: https://salaros.com

License: MIT License

C# 100.00%
configuration configuration-files file configuration-file config ini cfg configs conf mono dotnet managed csharp cross-platform

config-parser's Introduction

ConfigParser Build status AppVeyor tests branch Coverage Status

GitHub top language .NET Standard .NET Standard .NET Framework

License NuGet NuGet Pre Release NuGet

Donate Patreon Donate Paypal Donate Liberapay

ConfigParser - is a slim, cross-platform, fully managed C# library for reading and writing .ini, .conf, .cfg etc configuration files.

You could use it in your Unity 3D, Xamarin (iOS & Android), .NET Framework applications (even with old 4.0/4.5), .NET Core CLI and ASP.NET Core applications, Mono etc

Features

Customization

  • customizable encoding (most encodings can be auto-detected)
  • customizable culture
  • customizable number styles (e.g. currencies, exponential notation etc)
  • customizable line endings (usually auto-detected)
  • customizable true and false (e.g. "verum" / "falsum" )
  • customizable comment characters
  • customizable key/value separator (defaults to '=')

Read and preserved

  • file header comments
  • config files with no sections (like in this [SectionName]) or even mixed: first section has no header, just keys
  • comments in general
  • section comments
  • empty lines
  • indented sections
  • indented keys
  • indented values

Values

  • default values
  • multi-line values (both quoted and not)
  • quoted values
  • null values (value-less keys)
  • array values
  • fancy float / double
  • byte-encoded values
  • smart boolean values (0/1, on/off, enabled/disabled work of the box)

and more...

๐ŸŸŠ๐ŸŸŠ๐ŸŸŠ Support this project ๐ŸŸŠ๐ŸŸŠ๐ŸŸŠ

You can support us in a small way, please consider starring and sharing this repo! It helps us getting known and grow the community.

star us

Installation

Config Parser can be installed via NuGet by using Package Manager in your IDE, dotnet binary or Package Console

# Add the Salaros.ConfigParser package to a project named [<PROJECT>]
dotnet add [<PROJECT>] package Salaros.ConfigParser

or Visual Studio's Package Console

# Add the Salaros.ConfigParser package to the default project
Install-Package Salaros.ConfigParser

# Add the Salaros.ConfigParser package to a project named [<PROJECT>]
Install-Package Salaros.ConfigParser -ProjectName [<PROJECT>]

Usage

// Initialize config file instance from file
var configFileFromPath = new ConfigParser(@"path\to\configfile.cnf");

// Parse text
var configFileFromString = new ConfigParser(@"
    [Strings]
        canBeIndented = value
    andQuoted = ""quotes will be stripped""

    [Numbers]
    withD = 0.6D
    dollars = $2,999

    [boolean]
    numericTrue = 1
    textFalse = true
    yesWorks = yes
    upperCaseWorks = on
    worksAsWell = Enabled

    [Advanced]
    arrayWorkToo =
        arrayElement1
        arrayElement2
    valueLessKey",
    new ConfigParserSettings
    {
        MultiLineValues = MultiLineValues.Simple | MultiLineValues.AllowValuelessKeys | MultiLineValues.QuoteDelimitedValues,
        Culture = new CultureInfo("en-US")
    }
);

configFileFromString.GetValue("Strings", "canBeIndented");          // value
configFileFromString["Strings"]["canBeIndented"];                   // returns 'value' too
configFileFromString.GetValue("Strings", "andQuoted");              // quotes will be stripped

configFileFromString.GetValue("Numbers", "withD", 0D);              // 0,6
configFileFromString.GetValue("Numbers", "dollars", 0D,             // 2999
    NumberStyles.AllowCurrencySymbol);
configFileFromString.GetValue("Numbers", "dollars");                // $2,999

configFileFromString.GetValue("boolean", "numericTrue", false);     // True
configFileFromString.GetValue("boolean", "textFalse", false);       // True
configFileFromString.GetValue("boolean", "yesWorks", false);        // True
configFileFromString.GetValue("boolean", "upperCaseWorks", false);  // True
configFileFromString.GetValue("boolean", "worksAsWell", false);     // True

configFileFromString.GetArrayValue("Advanced", "arraysWorkToo");     // ["arrayElement1","arrayElement2"]
configFileFromString.GetValue("Advanced", "valueLessKey");          //

How to build

You need Git and .NET Core SDK

git clone https://github.com/salaros/ConfigParser
cd ConfigParser
dotnet build

How to test

ConfigParser uses xUnit.net, so you can run unit tests by simply using the following command:

dotnet test tests

License

ConfigParser is distributed under the MIT license, which grants you

  • Private use
  • Commercial use
  • Modification
  • Distribution

However you have to include the content of license file in your source code (if you distribute your Software in text form), otherwise include it in your own LICENSE file or to some sort of About -> Open-source libraries section if you distribute your Software as a compiled library / binary. Here is why (part of MIT license):

The above copyright notice and this permission notice 
shall be included in all copies or substantial portions of the Software.

config-parser's People

Contributors

salaros avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

config-parser's Issues

Allow dictionary/hashset-like sections

For example:

[Server]
Name = 192.168.0.1
[Server.Alpha]
Name = 192.168.0.2
IsAlpha = true
[Server.Beta]
Name = 192.168.0.3
IsBeta = true

If describe it as json, it would look something like this:

{
   "Server" : [
        {
             "Name" : "192.168.0.1",
             "Alpha": {
                    "Name" : "192.168.0.2",
                     "IsAlpha" : true
             },
             "Beta": {
                 "Name" : "192.168.0.3",
                "IsBeta" : "true",
             }
       }
   ]
}

Extend array declaration capabilities (with possible breaking change)

Currently, arrays can be declared only this way:
arrayWorkToo =
arrayElement1
arrayElement2

My suggestion is possibly remove such way of defining them (may be to make parsing a bit more strict), and instead allow these:
arrayWorkToo = [ 1, 2, 3 ]
arrayWorkToo = [ โ€œredโ€, โ€œyellowโ€, โ€œblackโ€ ]
arrayWorkToo = [ [ 1, 2 ], [3, 4, 5] ]
arrayWorkToo = [
arrayElement1,
arrayElement2
]
arrayWorkToo = [ { x = 1, y = 2, z = 3 },
{ x = 4, y = 5, z = 6} ]

Case insensitive parameter

It would be useful to be able to set a parameter that would allow case-insensitive reading and writing.

Allow \uXXXX to specify unicode symbols

Suggestion to add support for \uXXXX form (should be valid unicode scalar value) as the way to specify unicode symbols
For example:
[Temp]
name = "Windows"
name.company = "Microsoft \u00A9"

Because if we currently will try to write like this:
[Temp]
name = "Windows"
name.company = "Microsoft ยฉ"

We will get this message:
= No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Data = <enumerable Count: 0>
HelpLink =
HResult = -2146233067
InnerException =
Message = No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Source = System.Private.CoreLib
StackTrace = at System.Text.Encoding.GetEncoding(Int32 codepage)
at System.IO.FileInfoExtensions.IsInAnsiLatin1(FileInfo file, Double mangledCharThreshold)
at System.IO.FileInfoExtensions.TryGetEncoding(FileInfo file, Encoding& encoding)
at System.IO.FileInfoExtensions.GetEncoding(FileInfo file, Boolean throwIfNotDetected)
at Salaros.Configuration.ConfigParser..ctor(String configFile, ConfigParserSettings settings)

Lack of commenting?

Hello.
I've tried the usual characters (#, //) and none seems to work.
Not even if I read the config with the settings object with the CommentCharacters set to either // or #.

Is this intentional or am I missing something?

Wiki/tutorial is missing halfway

Hello
I see in the readme part how to read the values but how I can save for example a new file with new details? How I can modify one value or multiple values?
Sorry, I am very beginner and no idea how to use. For beginners would be nice to see at least the basic usage in every perspective which would be read (which already has), write and modify values.
Maybe I don't find this tutorial and already is there somewhere. If not then it would be nice to give overview how to use properly this.
Thank you in advance.

How to using config-parser without sections?

Hello, dear developer.
My .cfg file does not contain sections (like [section]). How i can using libary?
Error

************** ะขะตะบัั‚ ะธัะบะปัŽั‡ะตะฝะธั **************
Salaros.Configuration.ConfigParserException: This key value pair is orphan, all the keys must be preceded by a section.. On the line no. #2.
   at Salaros.Configuration.ConfigParser.BackupCurrentLine(ConfigSection& currentSection, ConfigLine& currentLine, Int32 lineNumber)
   at Salaros.Configuration.ConfigParser.ReadKeyAndValue(ConfigSection& currentSection, ConfigLine& currentLine, String lineRaw, Int32 lineNumber, Boolean append, Boolean forceIncludeKey)
   at Salaros.Configuration.ConfigParser.Read(String configContent)
   at Salaros.Configuration.ConfigParser..ctor(String configFile, ConfigParserSettings settings)
   at Launcher_CS.Form1.Form1_Load(Object sender, EventArgs e) in line 43
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Control.CreateControl(Boolean ignoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(HWND hWnd, MessageId msg, WPARAM wparam, LPARAM lparam)

Code:

            var configFileFromPath = new ConfigParser(@"config.cfg",
                new ConfigParserSettings
                {
                    KeyValueSeparator = " ",
                    MultiLineValues = MultiLineValues.QuoteDelimitedValues
                    
                });
            
            string CsName = configFileFromPath.GetValue(null, "name"); // Error

Hard to parse redis config file due to non section and space separated kv

Want:

parse redis config file to List

problem

the config-parser not friendly to none section and space separated kv config file

output

I tried to manually add a section name before the config file begins, and set separator to " ", but it raise exceptions

                var dict = new Dictionary<string, string>();
                raw.ConfigString = "[Fake]\n" + raw.ConfigString;
                this.logger.LogDebug($"redis config string: \n {raw.ConfigString}");
                var parserConfig = new ConfigParserSettings
                {
                    KeyValueSeparator = " ",
                    MultiLineValues = MultiLineValues.AllowValuelessKeys|MultiLineValues.AllowEmptyTopSection
                };
                var parser = new ConfigParser(raw.ConfigString, parserConfig);
                this.logger.LogDebug($"INI FILE SECTIONS: {string.Join(",", parser.Sections)}");
                this.logger.LogDebug($"INI FILE SECTION KEYS: {string.Join(",", parser.Sections[0].Keys)}");

out put:

 [Fake]
bind 11.1.1.11
port 12345
protected-mode no
daemonize yes
supervised no
loglevel notice
databases 16

tcp-backlog 16000
timeout 0
tcp-keepalive 60
maxclients 16000

maxmemory 6144MB
maxmemory-policy volatile-lru
save 300 10

stop-writes-on-bgsave-error no
rdbcompression yes
rdbchecksum yes

slave-serve-stale-data yes
slave-read-only yes
slave-priority 100
repl-ping-slave-period 10
repl-disable-tcp-nodelay no
min-slaves-to-write 0
min-slaves-max-lag 0

appendonly no
appendfsync everysec
aof-rewrite-incremental-fsync yes
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
no-appendfsync-on-rewrite no

hash-max-ziplist-entries 512
hash-max-ziplist-value 64

list-max-ziplist-entries 512
list-max-ziplist-value 64

set-max-intset-entries 512

zset-max-ziplist-entries 128
zset-max-ziplist-value 64
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 512mb 128mb 120
client-output-buffer-limit pubsub 32mb 8mb 60

cluster-enabled yes
cluster-node-timeout 30000
cluster-slave-validity-factor 10
cluster-migration-barrier 1
cluster-require-full-coverage yes
2020-12-09 10:10:56.487 +08:00 [WRN] =>[XXX.YYY.Redis.Controllers.RedisController]=> FetchInstanceConfig failed, System.ArgumentNullException: Value cannot be null. (Parameter 'separator')
   at Salaros.Configuration.ConfigKeyValue`1..ctor(String keyName, String separator, T value, Int32 lineNumber)
   at Salaros.Configuration.ConfigParser.ReadKeyAndValue(ConfigSection& currentSection, ConfigLine& currentLine, String lineRaw, Int32 lineNumber, Boolean append)
   at Salaros.Configuration.ConfigParser.Read(String configContent)
   at Salaros.Configuration.ConfigParser..ctor(String configFile, ConfigParserSettings settings)

Incorrect result of SetValue method

For example structure of my own config file:

[Settings]
Recno = chocolate

When I use SetValue and Save methods:

configFileFromPath.SetValue("Settings", "Recno", "123");
configFileFromPath.Save(@".\\config.ini");

...my config file look like that...

[Settings]
Recno = 123colate

...instead:

[Settings]
Recno = 123

support for redis multi line config

for example

client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 512mb 128mb 120
client-output-buffer-limit pubsub 32mb 8mb 60

each line of client-output-buffer-limit means different entry for config

expect

config.GetValue("client-output-buffer-limit")

returns

["normal 0 0 0", "slave 512mb 128mb 120", "pubsub 32mb 8mb 60"]

Add `ConfigParser.FileName` property

It would be a nice-to-have, to make working with LINQ queries easier, for when I specify the path to the filename, I'd like a read-only FileName property that is a string that contains the fully-qualified pathname of the data file being read ( blank if I just pass raw text to the constructor, of course).

How escape special char in values (e.g. separator)

Hello,
how I can escape "=" char in my value?

Example:

[Advanced]
Select =
	 select * from
	 from table
	 where ID = '5'

Array return only two first lines. Third line is ignored. I don't want change separator.

OR...

How to convert this multi-line value to one line (by ignoring carriage return)?

[Advanced]
ExampleValue = Lorem ipsum dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor incididunt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.