c#如何写入ini文件

时间:2013-06-18 06:26:47

标签: c# ini

我想知道如何将文本写入ini文件。已完成文件的读取。现在我只需要知道如何写入文件。

在INI文件中它应该如下所示:

[H83052_md7]
Description=H83048 processor mode 7
BootFile=kernel_52.md7
Extension=a20

如果你想看看我如何从文件中读取请问我的源代码,因为我无法弄清楚我应该怎么做。

我这样写:

namespace Flashloader

{ class Controllerlist : List<Controller> { public Controllerlist FromIniFile() { StringList input = new StringList().FromFile("Controllers.ini");

        Controller controller = null;

        foreach (var item in input)
        {
            String line = item.Trim();

            if (line.StartsWith("[") && line.EndsWith("]"))
            {
                String name = line.Substring(1, line.Length - 2);

                controller = new Controller(name);
                Add(controller);
            }
            else if (controller != null)
            {
                int index = line.IndexOf('=');
                if (index < 0)
                    continue;

                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if (Utils.EqualsIgnoreCase(key, "Description"))
                    controller.Description = value;
                else if (Utils.EqualsIgnoreCase(key, "Bootfile"))
                    controller.Bootfile = value;
                else if (Utils.EqualsIgnoreCase(key, "Extension"))
                    controller.Extension = value;
            }
        }
        return this;
    }

    public Controller FindByName(String name)
    {
        foreach (var item in this)
            if (Utils.EqualsIgnoreCase(item.Name, name))
                return item;
        return null;
    }
}

}

2 个答案:

答案 0 :(得分:2)

试试这堂课:

public class IniFile
  {
    public string path;

    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section,
      string key,string val,string filePath);

    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
      string key,string def, StringBuilder retVal,
      int size,string filePath);

    public IniFile(string INIPath)
    {
      path = INIPath;
    }

    public void IniWriteValue(string Section,string Key,string Value)
    {
      WritePrivateProfileString(Section,Key,Value,this.path);
    }

    public string IniReadValue(string Section,string Key)
    {
      StringBuilder temp = new StringBuilder(255);
      int i = GetPrivateProfileString(Section,Key,"",temp,255, this.path);
      return temp.ToString();
    }
  }

答案 1 :(得分:1)

这是写入/读取INi文件的最佳解决方案。 http://www.blackwasp.co.uk/IniFile.aspx