日期:2014-05-18  浏览次数:21089 次

关于C#使用API读取INI文件
[DllImport("kernel32")]
  //写INI文件API函数
 public static extern Int32 WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);
   
  [DllImport("kernel32")]
  //读INI文件API函数  
  public static extern Int32 GetPrivateProfileString(string lpApplicationName, string lpKeyName, string lpDefault, string lpReturnedString, Int32 nSize, string lpFileName);
  #endregion


 private string _INIFileName;
  public string INIFileName
  {
  get { return _INIFileName; }
  set { _INIFileName = value; }
  }

  public ClsINI(string INIFileName)
  {
  _INIFileName = INIFileName;
  }

  #region "读写指定键"
  //写指定键的值
  public bool Write(string SectionName, string KeyName, string Value)
  {
  try
  {
  WritePrivateProfileString(SectionName, KeyName, Value, _INIFileName);
  return true;
  }
  catch
  {
  return false;
  }
  }
 


//读指定键的值
   
  public string Read(string SectionName, string KeyName)
  {
  string returnValue;
  Int32 intRetval;
  string Strdata = new string(' ', 1024);
   
  try
  {
  intRetval = GetPrivateProfileString(SectionName, KeyName, null, Strdata, Strdata.Length, _INIFileName);
   
  if (intRetval > 0)
  {
   
  returnValue= Strdata.Substring(0, intRetval);
   
  }
   
  else
  {
  returnValue = "";
  }
  }
  catch
  {
  returnValue = "";
  }
  return returnValue;  
   
  }


写入INI文件是正常的,但在读取时returnValue值是NULL,错在哪里了?


------解决方案--------------------
看看KeyName在section里面存在不存在,跟踪下看是否有异常
------解决方案--------------------
XML code

[ServerVersion]
Deal=1.0.5.6
[ClientVersion]
Deal=1.0.5.6
[ServerUrl]
Deal=
[ReportPackUrl]
Deal=

------解决方案--------------------
探讨
[DllImport("kernel32")]
//写INI文件API函数
public static extern Int32 WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);

[DllImport("ker……

------解决方案--------------------
探讨
引用:
看看KeyName在section里面存在不存在,跟踪下看是否有异常


回得楼上存在的,keyname="connectionstring"
我想应该是string Strdata = new string(' ', 1024);这条语句定义出问题了,上面的代码是VB翻写来的(dim strdata=string.space(1024),因为C#没有space方……

------解决方案--------------------