读书人

关于C#使用API读取INI文件,该如何解决

发布时间: 2012-05-27 05:42:30 作者: rapoo

关于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方……

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


public static extern Int32 GetPrivateProfileString(string lpApplicationName, string lpKeyName, string lpDefault, ref string lpReturnedString, Int32 nSize, string lpFileName);
ref string lpReturnedString,加个ref。楼主试试。
或者用StringBuilder lpReturnedString。
猜想是因为字符串虽然是引用类型,但行为和值类型类似,所以没有引用到。

读书人网 >C#

热点推荐