-
ini文件读取
-
获取执行目录
-
App.config文件读取
-
系统信息
ini文件读取
-
ini文件是个啥?
.ini 文件是Initialization File的缩写,即初始化文件,是 windows 的系统配置文件所采用的存储格式,统管 windows 的各项配置,一般用户就用 windows 提供的各项图形化管理界面就可实现相同的配置了。
-
ini文件以什么格式存储数据?
[节点名称]
key1=value1
key2=value2
[其它节点]
key1=value1
key2=value2 -
C# winform项目中如何读写ini文件呢?
借助动态链接库kernel32.dll
kernel32.dll是Windows 9x/Me中非常重要的32位动态链接库文件,属于内核级文件。它控制着系统的内存管理、数据的输入输出操作和中断处理,当Windows启动时,kernel32.dll就驻留在内存中特定的写保护区域,使别的程序无法占用这个内存区域。
-
在winform项目中使用一个动态链接库的基本步骤?
动态链接库不需要引用,系统自带。
动态链接库提供的功能比较多,说明动态链接库中方法比较多。
a. 先导入动态链接库,其实本质上是导入的动态链接库中某个方法。 [DllImport("kernel32.dll")]
b. 就可以在C#代码中使用导入的动态链接库中的某个方法。
App.config文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="IniFilePath" value="C:\\test.ini"/>
</appSettings>
</configuration>
IniFileHelper类
定义了一个 IniFileReader 类,其中使用 DllImport 引入了 Windows API 函数来读取 ini 文件中的值。
namespace _1.ini文件读取.Helpers
{
public class IniFileHelper
{
private static string filePath = ConfigurationManager.AppSettings["IniFilePath"].ToString();
#region 导入动态链接库中方法
[DllImport("kernel32.dll")]
/// <summary>
/// 获取值
/// </summary>
/// <param name="section">段落名</param>
/// <param name="key">键名</param>
/// <param name="defval">读取异常是的缺省值</param>
/// <param name="retval">键名所对应的的值,没有找到返回空值</param>
/// <param name="size">返回值允许的大小</param>
/// <param name="filepath">ini文件的完整路径</param>
/// <returns></returns>
private static extern int GetPrivateProfileString(string section, string key, string defval, StringBuilder retval, int size, string filepath);
/// <summary>
/// 写入
/// </summary>
/// <param name="section">需要写入的段落名</param>
/// <param name="key">需要写入的键名</param>
/// <param name="val">写入值</param>
/// <param name="filepath">ini文件的完整路径</param>
/// <returns></returns>
[DllImport("kernel32.dll")]
private static extern int WritePrivateProfileString(string section, string key, string val, string filepath);
#endregion
/// <summary>
/// 读取Ini文件
/// </summary>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <returns>值</returns>
public static string ReadIniFile(string section, string key)
{
StringBuilder sb = new StringBuilder(1024);
GetPrivateProfileString(section, key, "", sb, 1024, filePath);
return sb.ToString();
}
/// <summary>
/// 写入Ini文件
/// </summary>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <param name="value"></param>
/// <returns></returns>
public static void WriteIniFile(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, filePath);
}
}
}
窗体设计
//保存
private void btnSave_Click(object sender, EventArgs e)
{
IniFileHelper.WriteIniFile("设备规格", "设备名称", txtSBMC.Text);
IniFileHelper.WriteIniFile("设备规格", "处理器", txtCLQ.Text);
IniFileHelper.WriteIniFile("设备规格", "机带RAM", txtJDRAM.Text);
IniFileHelper.WriteIniFile("设备规格", "设备ID", txtSBID.Text);
IniFileHelper.WriteIniFile("设备规格", "产品ID", txtCPID.Text);
IniFileHelper.WriteIniFile("设备规格", "系统类型", txtXTLX.Text);
IniFileHelper.WriteIniFile("设备规格", "笔和触控", txtBHCK.Text);
IniFileHelper.WriteIniFile("Windows规格", "版本", txtBB.Text);
IniFileHelper.WriteIniFile("Windows规格", "版本号", txtBBH.Text);
IniFileHelper.WriteIniFile("Windows规格", "安装日期", txtAZRQ.Text);
IniFileHelper.WriteIniFile("Windows规格", "操作系统版本", txtCZXTBB.Text);
IniFileHelper.WriteIniFile("Windows规格", "体验", txtTY.Text);
MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//读取
private void btnRead_Click(object sender, EventArgs e)
{
ReadIniFile();
MessageBox.Show("读取成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ReadIniFile()
{
txtSBMC.Text = IniFileHelper.ReadIniFile("设备规格", "设备名称");
txtCLQ.Text = IniFileHelper.ReadIniFile("设备规格", "处理器");
txtJDRAM.Text = IniFileHelper.ReadIniFile("设备规格", "机带RAM");
txtSBID.Text = IniFileHelper.ReadIniFile("设备规格", "设备ID");
txtCPID.Text = IniFileHelper.ReadIniFile("设备规格", "产品ID");
txtXTLX.Text = IniFileHelper.ReadIniFile("设备规格", "系统类型");
txtBHCK.Text = IniFileHelper.ReadIniFile("设备规格", "笔和触控");
txtBB.Text = IniFileHelper.ReadIniFile("Windows规格", "版本");
txtBBH.Text = IniFileHelper.ReadIniFile("Windows规格", "版本号");
txtAZRQ.Text = IniFileHelper.ReadIniFile("Windows规格", "安装日期");
txtCZXTBB.Text = IniFileHelper.ReadIniFile("Windows规格", "操作系统版本");
txtTY.Text = IniFileHelper.ReadIniFile("Windows规格", "体验");
}
获取执行目录
获取项目的执行路径
private void button1_Click(object sender, EventArgs e)
{
// 获取项目执行路径:bin/Debug
Console.WriteLine(Environment.CurrentDirectory);// 当前目录
Console.WriteLine(Directory.GetCurrentDirectory()); // 当前目录
Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); // 基目录
Console.WriteLine(Application.StartupPath);//启动路径
Console.WriteLine(Application.ExecutablePath);// 执行路径,带可执行文件 .exe
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
}
使用进程对象打开一个其它的软件
private void button2_Click(object sender, EventArgs e)
{
// Process进程,Start()方法可以启动系统中其他软件。
//Process.Start("C:\\Users\\dongshuhua\\Desktop\\C#软件开发\\15\\配置文件\\1.ini文件读取\\bin\\Debug\\1.ini文件读取.exe");
//Process.Start(@"C:\Program Files\Tencent\QQNT\QQ.exe");
Process.Start(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe");
}
动态设置图像
private void button3_Click(object sender, EventArgs e)
{
string path = Environment.CurrentDirectory;
string fullPath = Path.Combine(path, "..\\..\\","Images\\bd.png");
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.Image = Image.FromFile(fullPath);
}
App.config文件读取
配置文件App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<!--连接字符串,用来连接数据库用的。各种数据库都可以使用连接字符串-->
<connectionStrings>
<add name="SQLServer" connectionString="server=.;database=dong;uid=sa;pwd=123456;"/>
</connectionStrings>
<!--应用程序设置, 键值对-->
<appSettings>
<add key="Name" value="张三"/>
<add key="Age" value="20"/>
<add key="Sex" value="男"/>
</appSettings>
</configuration>
连接字符串(Connection String)主要用于建立与数据库的连接。它包含了连接数据库所需的各种参数信息,例如数据库服务器的名称、数据库的名称、认证方式(用户名和密码)、连接超时等。
AppConfigHelper.cs
namespace _3.App.config文件读取.Helpers
{
public static class AppConfigHelper
{
private static Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
//ConfigurationManager 是.NET 框架中的一个类,用于访问应用程序的配置信息。它提供了静态方法和属性来获取 App.config 或 Web.config 文件中的配置设置,例如 AppSettings 节和 ConnectionStrings 节中的信息。
public static string Get(string key, bool isConnectionString = false)
{
string result = null;
if (isConnectionString)
{
foreach (ConnectionStringSettings item in config.ConnectionStrings.ConnectionStrings)
{
if(item.Name== key)
{
result = ConfigurationManager.ConnectionStrings[key].ConnectionString;
break;
}
}
}
else
{
foreach (KeyValueConfigurationElement item in config.AppSettings.Settings)
{
if (item.Key == key)
{
result= ConfigurationManager.AppSettings[key];
break;
}
}
}
return result;
/*try
{
return isConnectionString ? ConfigurationManager.ConnectionStrings[key].ConnectionString : ConfigurationManager.AppSettings[key];
}
catch
{
return null;
}*/
}
public static void Add(string key, string value, bool isConnectionString = false)
{
if (isConnectionString)
{
if (Get(key, true) == null)
{
config.ConnectionStrings.ConnectionStrings.Add(
new ConnectionStringSettings(key, value)
);
}
else
{
config.ConnectionStrings.ConnectionStrings.Remove(key);
config.ConnectionStrings.ConnectionStrings.Add(
new ConnectionStringSettings(key, value)
);
}
}
else
{
if (Get(key) == null) config.AppSettings.Settings.Add(key, value);
else
{
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
}
}
config.Save();
}
public static void Remove(string key)
{
config.AppSettings.Settings.Remove(key);
}
public static void Clear()
{
config.AppSettings.Settings.Clear();
}
}
}
窗体设计
调用类里面的相应方法。
系统信息
窗体设计
//System.Timers.Timer timer;
public Form1()
{
InitializeComponent();
//timer.Elapsed += Timer_Elapsed;
}
/*private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
throw new NotImplementedException();
}*/
Microsoft.VisualBasic.Devices.Computer myInfo = new Microsoft.VisualBasic.Devices.Computer();
private void Form1_Load(object sender, EventArgs e)
{
lblCurrentTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
timer1.Interval = 1000; // 间隔时间,单位:毫秒
timer1.Tick += Timer1_Tick;
lblComputeName.Text = Environment.MachineName + " " + myInfo.Name;
// \n
//lblNewLine.Text = "HELLO" + Environment.NewLine + "World!";
lblNewLine.Text = "HELLO\nWorld!";
//TimeSpan time = TimeSpan.FromMilliseconds(Environment.TickCount);
TimeSpan time = TimeSpan.FromMilliseconds(myInfo.Clock.TickCount);
string timeStr = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
lblSystemStartTime.Text = timeStr;
lblDirectory.Text = Environment.CurrentDirectory;
// Operate System操作系统。
lblVersion.Text = Environment.OSVersion.ToString();
Console.WriteLine(Environment.OSVersion.VersionString);
Console.WriteLine(Environment.OSVersion.Platform);
Console.WriteLine(Environment.OSVersion.Version);
Console.WriteLine(Environment.OSVersion.ServicePack); // 补丁
lblCUPCount2.Text = Environment.ProcessorCount.ToString();
lblSystemType.Text = Environment.Is64BitOperatingSystem ? "64位" : "32位";
//获取物理内存总量
lblMemoryTotal.Text = (myInfo.Info.TotalPhysicalMemory / 1024 / 1024 / 1024D).ToString("0.0") + " GB";
//获取可用物理内存总量
lblMemoryAvailable.Text = (myInfo.Info.AvailablePhysicalMemory / 1024 / 1024 / 1024D).ToString("0.0") + " GB";
Console.WriteLine(myInfo.Screen.DeviceName);
}
private void Timer1_Tick(object sender, EventArgs e)
{
lblCurrentTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true; // 启动定时器
//timer1.Start(); // 启动定时器, 会执行定时器Tick事件
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false; // 禁用定时器
/*if (timer1.Enabled)
{
timer1.Stop();
}*/
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit(); // 应用程序退出
//this.Close();// 项目主窗体关闭也可以让应用程序退出
Environment.Exit(0); // 应用程序运行环境退出
}
标签:string,配置文件,C#,Text,void,key,IniFileHelper,config
From: https://www.cnblogs.com/dbsdb/p/18365090