将INI文件中的特定值读取到文本框中

本文关键字:读取 文本 INI 文件 | 更新日期: 2023-09-27 18:22:25

我需要能够读取INI文件的"Country="部分,并将值放在应用程序的文本框中吗?该文本框称为"cbxctry"。我已经考虑过使用streamreader,但不确定这是否正确?如果你需要任何进一步的信息,请告诉我。

INI文件

[Carrier]
Name=Singtel
ChargeStructure=Business Rates
CountryId=88
Country=Singapore
Ident=99101
MeterRate=0
DefaultChargeBand=N
NetworkDigits=
[CallCategories]
N=National
I=International
M=Mobile
L=Local
F=Free
P=Premium
DE=Directory Enquiries

代码

private void btnnewtariff_Click_1(object sender, EventArgs e)
{
    Stream myStream = null;
    SaveFileDialog openFileDialog1 = new SaveFileDialog();
    openFileDialog1.InitialDirectory = @"D:'tig2020'Carriers''";
    openFileDialog1.Filter = "inf files (*.Inf)|*.Inf|All files (*.*)|*.*";
    openFileDialog1.FilterIndex = 1;
    openFileDialog1.RestoreDirectory = false;
    openFileDialog1.OverwritePrompt = true;
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                using (myStream)
                {
                    txtnewtariff.Text = openFileDialog1.FileName;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
        }

将INI文件中的特定值读取到文本框中

这是我前段时间写的一个类,现在可能会增强很多,但它应该仍然可以正常工作。

该类使用WinApi GetPrivateProfileSectionNamesGetPrivateProfileSectionGetPrivateProfileStringWritePrivateProfileString,并从NET的角度提供了简单的工作方法。

文件iniUtil.cs

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Specialized;
/// <summary>
/// Class to read/write key values in a INI file
/// </summary>
public class iniUtil
{
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileSectionNames(byte[] lpszReturnBuffer, int nSize, string lpFileName);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string lpFileName);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileString(string lpApplicationName, string lpKeyName, string lpDefault, byte[] lpReturnedString, int nSize, string lpFileName);
    [DllImport("kernel32.dll")]
    private static extern bool WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);
    private const int VALUE_BUFFER = 511;
    private const int SECTION_BUFFER = (1024 * 16);
    private string m_sIniFile;
    /// <summary>
    /// .ctor with INI file name
    /// </summary>
    /// <param name="fileName">Fullpath to the INI file</param>
    public iniUtil(string fileName)
    {
        m_sIniFile = fileName;
    }
    /// <summary>
    /// Set the value for a specific key in a section
    /// </summary>
    /// <param name="section">Section containing the key to write to</param>
    /// <param name="key">Key to insert/update</param>
    /// <param name="keyvalue">Value for the key</param>
    /// <returns>True if OK</returns>
    public bool SetValue(string section, string key, string keyvalue)
    {
        return WritePrivateProfileString(section, key, keyvalue, m_sIniFile);
    }
    /// <summary>
    /// Gets the value of the specidied key in the specified section, 
    /// If the key doesn't exists returns the default value
    /// </summary>
    /// <param name="section">Section containing the key to read from</param>
    /// <param name="key">Required key</param>
    /// <param name="ifMissing">Value to return in case the key is missing</param>
    /// <returns>string value of the key or missing value</returns>
    public string GetValue(string section, string key, string ifMissing)
    {
        byte[] by = new byte[VALUE_BUFFER];
        int n = GetPrivateProfileString(section, key, ifMissing, by, VALUE_BUFFER, m_sIniFile);
        string s = Encoding.ASCII.GetString(by);
        return s.Substring(0, n);
    }
    /// <summary>
    /// Returns the NameValueCollection for every key in the section
    /// </summary>
    /// <param name="section">Section name</param>
    /// <returns>NameValueCollection with nake=Key and value=value</returns>
    public NameValueCollection GetSectionKeysvalues(string section)
    {
        NameValueCollection n = new NameValueCollection();
        if(section.Length > 0)
        {
            byte[] by = new byte[SECTION_BUFFER];
            int x = GetPrivateProfileSection(section, by, SECTION_BUFFER, m_sIniFile);
            if(x > 0) x--;
            string keysvalues = Encoding.ASCII.GetString(by, 0, x);
            string[] temp = keysvalues.Split(''0');
            foreach(string s in temp)
            {
                string[] t = s.Split('=');
                n.Add(t[0], t[1]);
            }
        }
        return n;
    }
    /// <summary>
    /// Get the names of all sections in .INI
    /// </summary>
    /// <returns>string array with all the key names</returns>
    public string[] GetSectionNames()
    {
        byte[] by = new byte[SECTION_BUFFER];
        int x = GetPrivateProfileSectionNames(by, SECTION_BUFFER, m_sIniFile);
        if(x > 0) x--;
        string keys = Encoding.ASCII.GetString(by, 0, x);
        return keys.Split(''0');
    }
}

在您的程序中,您调用。。。。。

iniUtil ini = new iniUtil(@"C:'program files (x86)'myapp'myapp.ini");
string country = ini.GetValue("Carrier","Country","NoCountry");