文章所用工具
http://t.csdnimg.cn/2gIR8
http://t.csdnimg.cn/2gIR8
搭建服务器界面
操作配置文件保存方式类
public string FileName { get; set; }
public IniHelper(string name)
{
this.FileName = name; //在构造函数中给路径赋值
}
1 先导入c语言进行读取操作ini文件的方法
GetPrivateProfileString() 获取ini配置文件的数据
//static 静态的变量 只能声明在当前文件中,不能在其他源文件进行使用。
//extern 用来声明外部的符号 可以跨文件使用。
[DllImport("Kernel32.dll")] //导入方法所在dll文件
public static extern Int32 GetPrivateProfileString(
string sectionName, //段名
string keyName,//键名
string defaultName,//当键不存在默认值。
StringBuilder returnValue,// 读取到数据
uint size,// 读取数据的大小
string fileName// ini文件路径
);
2添加写入ini文件的c方法
[DllImport("Kernel32.dll")]
public static extern Int32 WritePrivateProfileString(
string sectionName, //段名
string keyName,//键名
string value,//设置的值
string fileName// ini文件路径
);
不直接使用上面的俩个c语言的方法 再封装到其他方法进行使用
//读取ini数据的方法
//ReadData("Second","B","Setting.ini") "10"
//参数1 段名 ,参数2键名 ,参数3是文件路径
public static string ReadData(string sectionName,string keyName,string fileName)
{
StringBuilder sb = new StringBuilder(512); //512是存储的大小
GetPrivateProfileString(sectionName, keyName, string.Empty, sb, 512, fileName);
return sb.ToString();
}
对上面ReadData再封装,封装能直接返回指定类型的数据的方法
//传进段名和键名获取内容
//以后Read("段名","键名") 返回字符串类型
public string Read(string sectionName,string keyName)
{
return ReadData(sectionName, keyName,this.FileName);
}
如果读取数据 没读取到 给赋一个初值
Read("Secotion",A,"1000") 最终结果:hello world
Read("Secotion",C,"1000") 最终结果:1000
public string Read(string sectionName, string keyName,string defaultValue)
{
string v = Read(sectionName, keyName);
if (string.IsNullOrEmpty(v))
{
return defaultValue;
}
return v;
}
读取的时候 返回一个整型的数据值
Read("Secotion",C,1000) 最终结果:1000
Read("Secotion",A,1000) 最终结果:1000
public int Read(string s1, string k1, int d1)
{
string v = Read(s1, k1);
if (int.TryParse(v,out int value))
{
return value;
}
else
{
return d1;
}
}