C# 写配置文件(cfg)中的内容
1.如下图所示,假如我们想要在代码中改变General下的Port端口值,那么需要如下步骤:
2.在program类中添加如下几句代码:
using System.Runtime.InteropServices;(引用)
[DllImport("kernel32")]
public static extern int WritePrivateProfileString(string section, string key, string str, string filePath);
3.完整代码如下:刚开始我们读配置文档中串口的值为8000,后面写成8004,再次读串口的值会发现已经变成了8004.
在program.cs类中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.Runtime.InteropServices;
namespace AOI_demo
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
#region 读配置文档中的内容
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
#endregion
#region 写配置文档中的内容
[DllImport("kernel32")]
public static extern int WritePrivateProfileString(string section, string key, string str, string filePath);
#endregion
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form2());
}
}
}
在窗体程序中:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AOI_demo
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
#region 读配置文档中串口的值
string path = Application.StartupPath + @"\app.cfg";//配置文档中的地址
StringBuilder sb = new StringBuilder(512);
Program.GetPrivateProfileString("General", "Port", "", sb, 512, path);
string str = sb.ToString();//str=8000
Console.WriteLine(str);
#endregion
#region 向配置文档中写值
Program.WritePrivateProfileString("General", "Port", "8004", path);//写值
#endregion
#region 再次读值
Program.GetPrivateProfileString("General", "Port", "", sb, 512, path);
str = sb.ToString();//str=8004
Console.WriteLine(str);
#endregion
}
}
}