根据网上资料抄了如下读写INI的一个函数    //读写INI
    public class MyINI
    {
        public string inipath;
        [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 MyINI(string INIPath)
        {
            inipath = INIPath;
        }
        // 写入INI文件 
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.inipath);
        }
        // 读出INI文件
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, Key, "未发现有指定值", temp, 500, this.inipath);
            return temp.ToString();
        }
        //验证文件是否存在 
        public bool ExistINIFile()
        {
            return File.Exists(inipath);
        }
    }调用如下:
        MyINI nn=new MyINI(Server.MapPath(@"~/bak.ini"));
        if (nn.ExistINIFile())
        {
            Label1.Text = nn.IniReadValue("Section1", "KeyWord2");
        }
        else
        {
            Label1.Text = "未找到文件";
        }
为什么取不到值呢?
文件也存在,显示:未发现有指定值
bak.ini的内容如下
[Section1]
  KeyWord1 = Valuel
  KeyWord2 = Value2

解决方案 »

  1.   

    dllimport里加上SetLastError,看errorcode是什么。
      

  2.   


    我加了SetLastError,请问在什么地方可以看到errorcode?
      

  3.   

            public void WriteInivalue(string Section, string Key, string value)
            {
                WritePrivateProfileString(Section, Key, value, System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "SysMsg.ini");
            }        public string ReadInivalue(string Section, string Key)
            {
                StringBuilder TempStr = new StringBuilder(2000);
                int i = GetPrivateProfileString(Section, Key, "", TempStr, 2000, System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "SysMsg.ini");
                return TempStr.ToString();
            }