我无法使用 C# 读取文件 .ini

I can not reading file .ini with C#

我有一个问题,不太明白。我已阅读文章 Reading/writing an INI file 我已经将它应用到我的项目中。但我无法读取 .int 文件中的数据。

这是我使用的代码

var MyIni = new IniFile("config.ini");
                string id = MyIni.Read("id").ToString();
                string url = MyIni.Read("url").ToString();
                string token = MyIni.Read("token").ToString();

这是我用的class“IniFile.cs”

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

// Change this to match your program's normal namespace
namespace MyProg
{
class IniFile   // revision 11
{
    string Path;
    string EXE = Assembly.GetExecutingAssembly().GetName().Name;

    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

    public IniFile(string IniPath = null)
    {
        Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
    }

    public string Read(string Key, string Section = null)
    {
        var RetVal = new StringBuilder(255);
        GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
        return RetVal.ToString();
    }

    public void Write(string Key, string Value, string Section = null)
    {
        WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
    }

    public void DeleteKey(string Key, string Section = null)
    {
        Write(Key, null, Section ?? EXE);
    }

    public void DeleteSection(string Section = null)
    {
        Write(null, null, Section ?? EXE);
    }

    public bool KeyExists(string Key, string Section = null)
    {
        return Read(Key, Section).Length > 0;
    }
}

}

这是我的“IniFile.ini”

中的信息

id=5eb3c344a9e9486ebb3450cd 
url=https:https://demo.cti.com/
token=FO_KO7XTNe6tamWL9PlFG7L5gbGObl4z

我将文件“IniFile.ini”放在项目的“调试”文件夹中。希望大家帮帮我,我这是怎么了?非常感谢!

使用 GetPrivateProfileString 的节参数获取 NULL 并不意味着从 INI 文件的无节键中获取值。(https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilestring)

所以,您可以使您的 .ini 像

[config]
id=5eb3c344a9e9486ebb3450cd 
url=https:https://demo.cti.com/
token=FO_KO7XTNe6tamWL9PlFG7L5gbGObl4z

然后

string id = MyIni.Read("id", "config").ToString();
string url = MyIni.Read("url", "config").ToString();
string token = MyIni.Read("token", "config").ToString();

而且效果会很好。

要点是,GetPrivateProfileString 无法处理无节 INI 文件。您可能需要其他图书馆来处理。