簡體   English   中英

.ini 文件解析器 C#

[英].ini file parser C#

我在一個迷你項目中工作(.ini 文件解析器)。 我非常需要你的幫助。 他是我的代碼,但我得到一個空白結果!

  public string READ_VALUE(string SECTION, string KEY , string PATH)
    {
        foreach (string READER_LINE in File.ReadAllLines(PATH))
        {
            if (READER_LINE == SECTION)
            {
                if (READER_LINE == KEY)
                {
                    return READER_LINE;
                }
            }
        }
        return "";
    }

采用:

string ini_parser = READ_VALUE("SECTION_1", "ASD_1" , @"C:\SETTINGS.ini");

這是我的 file.ini:

[SECTION_1]
ASD_1=12345
ASD_2=12345
ASD_3=12345
[SECTION_2]
ASD_1=12345
ASD_2=12345
ASD_3=12345
[SECTION_3]
ASD_1=12345
ASD_2=12345
ASD_3=12345

正如其他人所說,除了 INI 之外,還有其他方法可以執行此操作或使用其他格式,請查看以下內容 - 我以類似於您的風格重寫了您的方法的內部結構

public string READ_VALUE(string SECTION, string KEY, string PATH, string DEFAULT_VALUE = "")
{
    // read all lines from the file
    string[] READER_LINES = File.ReadAllLines(PATH);

    // we are going to capture the value of a "section" line here, so we can 
    // test to see if subsequent lines belong to the section we are
    // looking for
    string CURRENT_SECTION = "";

    // itterate all the lines until we find the section and key we want
    foreach(string READER_LINE in READER_LINES)
    {
        // detect if the line is a [SECTION_NAME] and capture it as the current section
        if(READER_LINE.StartsWith("[") && READER_LINE.EndsWith("]"))
        {
            CURRENT_SECTION = READER_LINE;
        }
        else if (CURRENT_SECTION.Equals($"[{SECTION}]"))
        {
            // The current line is not a section header

            // The current section is the section we are looking for, so lets process 
            // the lines within it

            // now lets split the current line into a key/value pair using = as the delimitor
            string[] lineParts = READER_LINE.Split(new[] { '=' }, 2);

            // test if part 1 of the line matches the KEY we are looking for
            if(lineParts.Length >= 1 && lineParts[0] == KEY)
            {
                // we have found the key.
                // now return part 2 of the line as the value, or DEFAULT_VALUE if the split 
                // operation above could not find a part 2 to add to the list
                return lineParts.Length >= 2
                    ? lineParts[1]
                    : DEFAULT_VALUE;
            }
        }
    }

    // we have not found a match, so return the default value instead
    return DEFAULT_VALUE;
}

您的呼叫波紋管現在按預期工作(從您的 INI 文件返回 12345):

string ini_parser = READ_VALUE("SECTION_1", "ASD_1" , @"C:\\SETTINGS.ini");

作為額外的獎勵,您可能已經注意到額外的可選 DEFAULT_VALUE 參數:)

以下示例使用不在您的文件中的 KEY 值調用該方法。 在這種情況下,該方法返回“00000”的 DEFAULT_VALUE。

string ini_parser = READ_VALUE("SECTION_1", "UNKNOWN_KEY_NAME" , @"C:\\SETTINGS.ini", "00000");

希望有所幫助。

試試這個:

/// <summary>
/// A class for reading values by section and key from a standard ".ini" initialization file.
/// </summary>
/// <remarks>
/// Section and key names are not case-sensitive. Values are loaded into a hash table for fast access.
/// Use <see cref="GetAllValues"/> to read multiple values that share the same section and key.
/// Sections in the initialization file must have the following form:
/// <code>
///     ; comment line
///     [section]
///     key=value
/// </code>
/// </remarks>
public class IniFile
{
    /// <summary>
    /// Initializes a new instance of the <see cref="IniFile"/> class.
    /// </summary>
    /// <param name="file">The initialization file path.</param>
    /// <param name="commentDelimiter">The comment delimiter string (default value is ";").
    /// </param>
    public IniFile(string file, string commentDelimiter = ";")
    {
        CommentDelimiter = commentDelimiter;
        TheFile = file;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="IniFile"/> class.
    /// </summary>
    public IniFile()
    {
        CommentDelimiter = ";";
    }

    /// <summary>
    /// The comment delimiter string (default value is ";").
    /// </summary>
    public string CommentDelimiter { get; set; }

    private string theFile = null;

    /// <summary>
    /// The initialization file path.
    /// </summary>
    public string TheFile
    {
        get
        {
            return theFile;
        }
        set
        {
            theFile = null;
            dictionary.Clear();
            if (File.Exists(value))
            {
                theFile = value;
                using (StreamReader sr = new StreamReader(theFile))
                {
                    string line, section = "";
                    while ((line = sr.ReadLine()) != null)
                    {
                        line = line.Trim();
                        if (line.Length == 0) continue;  // empty line
                        if (!string.IsNullOrEmpty(CommentDelimiter) && line.StartsWith(CommentDelimiter))
                            continue;  // comment

                        if (line.StartsWith("[") && line.Contains("]"))  // [section]
                        {
                            int index = line.IndexOf(']');
                            section = line.Substring(1, index - 1).Trim();
                            continue;
                        }

                        if (line.Contains("="))  // key=value
                        {
                            int index = line.IndexOf('=');
                            string key = line.Substring(0, index).Trim();
                            string val = line.Substring(index + 1).Trim();
                            string key2 = string.Format("[{0}]{1}", section, key).ToLower();

                            if (val.StartsWith("\"") && val.EndsWith("\""))  // strip quotes
                                val = val.Substring(1, val.Length - 2);

                            if (dictionary.ContainsKey(key2))  // multiple values can share the same key
                            {
                                index = 1;
                                string key3;
                                while (true)
                                {
                                    key3 = string.Format("{0}~{1}", key2, ++index);
                                    if (!dictionary.ContainsKey(key3))
                                    {
                                        dictionary.Add(key3, val);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                dictionary.Add(key2, val);
                            }
                        }
                    }
                }
            }
        }
    }

    // "[section]key"   -> "value1"
    // "[section]key~2" -> "value2"
    // "[section]key~3" -> "value3"
    private Dictionary<string, string> dictionary = new Dictionary<string, string>();

    private bool TryGetValue(string section, string key, out string value)
    {
        string key2;
        if (section.StartsWith("["))
            key2 = String.Format("{0}{1}", section, key);
        else
            key2 = string.Format("[{0}]{1}", section, key);

        return dictionary.TryGetValue(key2.ToLower(), out value);
    }

    /// <summary>
    /// Gets a string value by section and key.
    /// </summary>
    /// <param name="section">The section.</param>
    /// <param name="key">The key.</param>
    /// <param name="defaultValue">The default value.</param>
    /// <returns>The value.</returns>
    /// <seealso cref="GetAllValues"/>
    public string GetValue(string section, string key, string defaultValue = "")
    {
        string value;
        if (!TryGetValue(section, key, out value))
            return defaultValue;

        return value;
    }

    /// <summary>
    /// Gets a string value by section and key.
    /// </summary>
    /// <param name="section">The section.</param>
    /// <param name="key">The key.</param>
    /// <returns>The value.</returns>
    /// <seealso cref="GetValue"/>
    public string this[string section, string key]
    {
        get
        {
            return GetValue(section, key);
        }
    }

    /// <summary>
    /// Gets an integer value by section and key.
    /// </summary>
    /// <param name="section">The section.</param>
    /// <param name="key">The key.</param>
    /// <param name="defaultValue">The default value.</param>
    /// <param name="minValue">Optional minimum value to be enforced.</param>
    /// <param name="maxValue">Optional maximum value to be enforced.</param>
    /// <returns>The value.</returns>
    public int GetInteger(string section, string key, int defaultValue = 0,
        int minValue = int.MinValue, int maxValue = int.MaxValue)
    {
        string stringValue;
        if (!TryGetValue(section, key, out stringValue))
            return defaultValue;

        int value;
        if (!int.TryParse(stringValue, out value))
        {
            double dvalue;
            if (!double.TryParse(stringValue, out dvalue))
                return defaultValue;
            value = (int)dvalue;
        }

        if (value < minValue)
            value = minValue;
        if (value > maxValue)
            value = maxValue;
        return value;
    }

    /// <summary>
    /// Gets a double floating-point value by section and key.
    /// </summary>
    /// <param name="section">The section.</param>
    /// <param name="key">The key.</param>
    /// <param name="defaultValue">The default value.</param>
    /// <param name="minValue">Optional minimum value to be enforced.</param>
    /// <param name="maxValue">Optional maximum value to be enforced.</param>
    /// <returns>The value.</returns>
    public double GetDouble(string section, string key, double defaultValue = 0,
        double minValue = double.MinValue, double maxValue = double.MaxValue)
    {
        string stringValue;
        if (!TryGetValue(section, key, out stringValue))
            return defaultValue;

        double value;
        if (!double.TryParse(stringValue, out value))
            return defaultValue;

        if (value < minValue)
            value = minValue;
        if (value > maxValue)
            value = maxValue;
        return value;
    }

    /// <summary>
    /// Gets a boolean value by section and key.
    /// </summary>
    /// <param name="section">The section.</param>
    /// <param name="key">The key.</param>
    /// <param name="defaultValue">The default value.</param>
    /// <returns>The value.</returns>
    public bool GetBoolean(string section, string key, bool defaultValue = false)
    {
        string stringValue;
        if (!TryGetValue(section, key, out stringValue))
            return defaultValue;

        return (stringValue != "0" && !stringValue.StartsWith("f", true, null));
    }

    /// <summary>
    /// Gets an array of string values by section and key.
    /// </summary>
    /// <param name="section">The section.</param>
    /// <param name="key">The key.</param>
    /// <returns>The array of values, or null if none found.</returns>
    /// <seealso cref="GetValue"/>
    public string[] GetAllValues(string section, string key)
    {
        string key2, key3, value;
        if (section.StartsWith("["))
            key2 = String.Format("{0}{1}", section, key).ToLower();
        else
            key2 = String.Format("[{0}]{1}", section, key).ToLower();

        if (!dictionary.TryGetValue(key2, out value))
            return null;

        List<string> values = new List<string>();
        values.Add(value);
        int index = 1;
        while (true)
        {
            key3 = String.Format("{0}~{1}", key2, ++index);
            if (!dictionary.TryGetValue(key3, out value))
                break;
            values.Add(value);
        }

        return values.ToArray();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM