C# 读配置文件(cfg)中的内容
1.在写程序的过程中,为了方便代码的修改,我们常常写一个配置文件。
2.配置文件放置的路径和其中的内容:
配置文件中的内容:
3.程序代码:
(1).在程序的Program.cs中加入三行代码:
using System.Runtime.InteropServices;
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section,string key, string def, StringBuilder retVal,int size, string filePath);
(2).在form1.cs中的引用示例如下:
public static string g_iniPath;
public static string g_OutputPath;
//g_iniPath=@"E:\ZhuW\Personal\CSharp\yolov3小程序合集\wfm_cfg\wfm_cfg\bin\Debug\app.cfg";
g_iniPath = Application.StartupPath + @"\app.cfg";
StringBuilder stringBuilder = new StringBuilder(512);
//"General"是配置文件中用中括号引起来的,"OutputPath"是"General"下的内容,读到的数据存储在stringBuilder中,最后将stringBuilder数据转换陈string类型并赋值给g_OutputPath。
Program.GetPrivateProfileString("General", "OutputPath", "", stringBuilder, 512, g_iniPath);
g_OutputPath = stringBuilder.ToString();
(3)完整代码:
//Program.cs中的内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wfm_cfg
{
internal static class Program
{
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section,string key, string def, StringBuilder retVal,int size, string filePath);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using System.IO;
namespace wfm_cfg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string g_iniPath;
public static string g_OutputPath;
private void button1_Click(object sender, EventArgs e)
{
//g_iniPath=@"E:\ZhuW\Personal\CSharp\yolov3小程序合集\wfm_cfg\wfm_cfg\bin\Debug\app.cfg";
g_iniPath = Application.StartupPath + @"\app.cfg";
//(1)示例一
StringBuilder stringBuilder = new StringBuilder(512);
Program.GetPrivateProfileString("General", "OutputPath", "", stringBuilder, 512, g_iniPath);
g_OutputPath = stringBuilder.ToString();//“E:\\Date”
if (!Directory.Exists(g_OutputPath)) { Directory.CreateDirectory(g_OutputPath); }
//(2)示例二
StringBuilder PreCut = new StringBuilder(512);
Program.GetPrivateProfileString("DIM", "PreCut1", "", PreCut, 512, g_iniPath);
string a= PreCut.ToString();//"3566,2698,10000,46000"
}
}
}