【问题标题】:How to include spaces between equal sign when working with ini files c#?使用ini文件c#时如何在等号之间包含空格?
【发布时间】:2015-07-17 16:21:40
【问题描述】:

您好,我有一个格式如下的ini文件

[Text]
abcd = 1234
text = 1002
some = 4414
last = 1824

但是当我使用inifile类时,我在网上找到了一个用于处理ini文件的类:

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

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

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

        [DllImport("kernel32")]
        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.ToString();
        }

        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;
        }
    }
}

它可以添加到 ini 文件中,但格式如下:

test=0010

除了写入函数创建的函数之外,读取函数也不起作用。

如何更改代码以便在等号前后放置空格?在值之前添加一个空格,但在键之后添加一个空格无效。我也很犹豫在值中添加空格,因为我担心它可能会改变实际值并使我使用它的操作变得可读。

任何见解将不胜感激,谢谢。

【问题讨论】:

  • 我使用过的任何.ini 文件在键、= 和值之间都没有空格。我认为这是非常标准的。除了可读性之外,您还有其他原因想要这样做吗?
  • 如果您的“ini 文件”是以非标准格式编写的,您应该更正它。或者你可以编写自己的ini-class..
  • ini 文件不是属性文件。如果你想要 k = v 所以你必须修剪()它们并接受你的键或值在字符串的开头和结尾不包含空格。如果你想要自定义ini文件,pm我,我会给你我的ini课程的源代码,也许12小时后
  • 我也收到了这个 INI 文件的任务,我没有创建它。我不知道如何在这里私信,但如果可以的话,将不胜感激,谢谢!

标签: c# ini


【解决方案1】:

这是另一个 IniFile 类,可以让您实现该间距:https://github.com/MarioZ/MadMilkman.Ini

您需要做的是提供具有所需格式的 IniOptions,如下所示:

IniOptions options = new IniOptions();
options.KeySpaceAroundDelimiter = true;

IniFile ini = new IniFile(options);
ini.Load("path to your input INI file");

// Do something with file's sections and their keys ...

ini.Save("path to your output INI file");

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 2013-11-27
    • 2012-10-15
    • 2017-06-01
    • 2016-01-09
    • 2017-10-25
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    相关资源
    最近更新 更多