2013-06-27 28 views
1

我必須在我的項目中使用INI文件來存儲一些數據。所以我在我的項目中用不同的命名空間創建了一個類。現在當我嘗試執行我的項目時,我收到了這個錯誤。我正在使用Microsoft Visual C#2010 Express。我的代碼是:試圖讀取或寫入受保護的內存。這通常表明在創建INI文件時其他內存已損壞

namespace Ini 
{ 
    public class IniFile 
    { 
     public string path; 

     [DllImport("kernel32")] 
     private static extern long WritePrivateProfileString(string section, 
      string key,int 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, int 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(); 

     } 
    } 

} 

,我在我的主要項目中使用這個.. using Ini; (in namespace)

IniFile MyIni = new IniFile("D:\\Database.ini"); 
MyIni.IniWriteValue("ProductBase", "Key", 1); 

(在我的代碼)

+0

的文檔有這樣一段話:「只適用於Windows的16位版本的兼容性提供此功能。應用程序應該在註冊表中存儲初始化信息「也許使用不需要調用'kernel32.dll'的API?在一個普通的應用程序中看起來很奇怪 – millimoose

回答

2

正如你可以在documentation和上看到p/invoke.net,WritePrivateProfileString()有四個字符串參數,所以請將您的定義更改爲

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

和使用情況,以

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

yeahh它的工作原理.. !!! 非常感謝: ) – Lany

+0

是啊sure..its done :) – Lany

相關問題