Reading/writing an INI file

后端 未结 16 2392
南旧
南旧 2020-11-22 00:15

Is there any class in the .NET framework that can read/write standard .ini files:

[Section]
=
...

Delphi has th

16条回答
  •  死守一世寂寞
    2020-11-22 00:48

    If you want just a simple reader without sections and any other dlls here is simple solution:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Tool
    {
        public class Config
        {
            Dictionary  values;
            public Config (string path)
            {
                values = File.ReadLines(path)
                .Where(line => (!String.IsNullOrWhiteSpace(line) && !line.StartsWith("#")))
                .Select(line => line.Split(new char[] { '=' }, 2, 0))
                .ToDictionary(parts => parts[0].Trim(), parts => parts.Length>1?parts[1].Trim():null);
            }
            public string Value (string name, string value=null)
            {
                if (values!=null && values.ContainsKey(name))
                {
                    return values[name];
                }
                return value;
            }
        }
    }
    

    Usage sample:

        file = new Tool.Config (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\config.ini");
        command = file.Value ("command");
        action = file.Value ("action");
        string value;
        //second parameter is default value if no key found with this name
        value = file.Value("debug","true");
        this.debug = (value.ToLower()=="true" || value== "1");
        value = file.Value("plain", "false");
        this.plain = (value.ToLower() == "true" || value == "1");
    

    Config file content meanwhile (as you see supports # symbol for line comment):

    #command to run
    command = php
    
    #default script
    action = index.php
    
    #debug mode
    #debug = true
    
    #plain text mode
    #plain = false
    
    #icon = favico.ico
    

提交回复
热议问题