c# winform 关于.ini文件内容的修改与查找 5
wsdl=http://172.30.0.15:9080/g3_bs/services/webserver?wsdl
url=http://172.30.0.15:9080/g3_bs/services/webserver
port=CXFServiceImplPort
service=CXFServiceImplService
downloadurl=http://172.30.0.15:9080/g3_bs/download2 展开
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace PIS.Center.LocalStorage
{
internal class IniOperator
{
//声明kernel32.dll函数
private readonly String _iniPath;
/// <summary>
/// 构造方法
/// </summary>
public IniOperator()
{
_iniPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "local.db");
if (!File.Exists(_iniPath))
{
using (File.Create(_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);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(String section, String key, String defVal, Byte[] retVal, int size, String filePath);
[DllImport("kernel32")]
private static extern uint GetLastError();
/// <summary>
/// 写入INI文件
/// </summary>
/// <param name="section">Section</param>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
public void IniWriteValue(String section, String key, String value)
{
UInt32 snapshot = GetLastError();
WritePrivateProfileString(section, key, value, _iniPath);
if (snapshot != GetLastError())
{
Console.WriteLine("GetLastError :" + GetLastError());
}
}
/// <summary>
/// 读出INI文件
/// </summary>
/// <param name="section">Section</param>
/// <param name="key">Key</param>
public String IniReadValue(String section, String key)
{
var result = new StringBuilder(256);
GetPrivateProfileString(section, key, null, result, 256, _iniPath);
return result.ToString();
}
public String[] IniReadSection()
{
var sectionBytes = new Byte[255];
GetPrivateProfileString(null, null, "", sectionBytes, 255, _iniPath);
//编码所有key的String类型
var sectionString = new ASCIIEncoding().GetString(sectionBytes);
//获取key的数组
return sectionString.Split(new char[1] { '\0' });
}
public String[] IniReadKeys(String section)
{
var keyBytes = new Byte[255];
GetPrivateProfileString(section, null, "", keyBytes, 255, _iniPath);
//编码所有key的String类型
var keyString = new ASCIIEncoding().GetString(keyBytes);
//获取key的数组
return keyString.Split(new char[1] { '\0' });
}
}
}
参照这个类,对根据section和key取出值,修改后再次写入
2024-07-18 广告
2.文件大(超过几M)的话,新建一个文件,然后按块读取ini, 使用replace 写入到新文件中 ,重复知道ini 结束; 将 ini 删除,将新文件重命名为ini ok
iniStr.Replace("172.30.15:9080", "172.30.0.14:8080");
System.IO.File.OpenWrite("路径");