2013-06-18 57 views
0

我想知道我應該如何將文本寫入ini文件。該文件的閱讀已完成。現在我只需要知道如何寫入文件。c#如何寫入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

試試這個類:

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(); 
    } 
    } 
+0

爲什麼你有內核32件事? –

+0

您可以使用Windows API函數,因此您不必重新發明輪子。 – Robert

1

這是寫的最好的解決方案/閱讀INi文件。 http://www.blackwasp.co.uk/IniFile.aspx

+0

是內核32你正在寫的文件 –

+0

謝謝,但爲什麼在文件中有一個文本內核32它代表什麼。 –

+0

你在哪裏看到它?只有dllimport屬性有kernel32 –