C#读写INI文件

C#关于读写INI文件 C#关于读写INI文件 什么是ini文件就是一个配置文件,一般把数据库等配置信息放进去,然而,改变数据库的密码,数据库名称,ip等,不要改源码重新编译,只需要用记事本打开set.ini 文件,修改保存即可,不需要修改exe文件,你也修改不了, 跟java的数据库配置信息的properties文件类似或者springboot的yaml文件类似,软编码的抽取,我的数据库配置随时可能动,war包jar包不要动,的好处。 格式是 [Section] 段落 key(键)=value(值) 跟java的HashMap类 阅读详情

  虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。
  INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value):
  [Section]  Key=Value
  VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。

INIFILE类:
using System;
using System.IO;
using System.Runtime.InteropServices;
因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。

using System.Text;
namespace Ini{
    public class IniFile
    {
        public string path;    //INI文件名
        [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);        //声明读写INI文件的API函数
        public IniFile(string INIPath)
        {
            path = INIPath;
        }        //类的构造函数,传递INI文件名
        publicvoid IniWriteValue(string Section,string Key,string Value)
        {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }        //写INI文件
        publicstring IniReadValue(string Section,string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);
            return temp.ToString();
        }        //读取INI文件指定
    }
}
调用INIFILE类:

新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。

增加如下代码:
using Ini;  //创建命名空间//当窗体关闭时保存窗体坐标
privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
 IniFile ini = new IniFile("C://test.ini");
 ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString());
 ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString()); //ToString方法将数字转换为字符串}//当窗体启动时,读取INI文件的值并赋值给窗体
privatevoid Form1_Load(object sender, System.EventArgs e)
{
 IniFile ini = new IniFile("C://test.ini");
 Point p=new Point(); //判断返回值,避免第一次运行时为空出错
 if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))
 {
  p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));
  p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));  // int.Parse将字符串转换为int    this.Location =p;
 }
} 

C#读写Ini文件类 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Collections.Specialized;using System.IO;using System.Runtime.InteropServices;using System.Windows.Forms;namespace Comm{    ///     /// IniFiles的类    ///     publ 阅读详情

相关推荐

C#中ini文件的读写操作详解

ini文件,全称为Initialization File,是一种简单的配置文件格式,广泛应用于软件设置和配置信息的存储。它通常由简单的文本组成,分为节(Sections)和键值对(Key-Value Pairs),便于人类阅读和编辑。由于其结构简单、容易解析,ini文件成为了应用程序配置管理的首选。自定义配置节允许开发者为应用程序扩展配置文件的功能,通过创建自己的配置节处理器来解析和管理这些自定义节。这一过程涉及定义配置节的schema以及编写代码以处理这些配置项。

weixin_35752233的博客 1593

如何在C#中读写INI文件

但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。这里有一点应该注意,当在调用WritePrivateProfileString()对INI文件进行写操作的时候,如果此时在INI文件中存在和要写入的信息相同的段落名称和关键字,则将覆盖此INI信息。通过上面的这些介绍,可以看成C#操作INI文件的过程,其实就是C#调用Win32的API函数的过程。

biyusr的专栏 1748

让 AI 变聪明的 20 条指令:如何让大模型回答得更精准、更专业、更实事求是

让 AI 变聪明,本质上不是写几句神奇咒语,而是把你的任务表达得更清楚,把事实标准设得更严格,把输出格式规定得更明确,把不确定性管理得更认真,把历史对话利用得更充分。大模型的强项是语言生成、信息组织、模式归纳和方案扩展;弱项是事实核验、实时更新、责任判断和对模糊意图的准确猜测。好的指令,就是在用人的判断弥补模型的弱点,让模型把强项发挥在正确的地方。

Sumarua的博客 1597

C#读写ini文件详解

C#读写ini文件是如何进行的呢?C#读写ini文件需要的方法有哪些呢?本文就向你一一介绍。 C#读写ini文件之前要了解的概念:INI就是扩展名为"INI"的文件,其实他本身是个文本文件,可以用记事本打开,主要存放的是用户所做的选择或系统的各种参数. C#读写ini文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,...

weixin_30328063的博客 1825

控制障碍函数(Control Barrier Function,CBF) 二、示例

使用一个经典简单的示例讲解CBF的推导

Lyajpunov的博客 6441

基于STM32与CAN总线的多电机协同控制系统设计与实现

本文详细介绍了基于STM32与CAN总线的多电机协同控制系统设计与实现。该系统采用分布式架构,通过CAN总线实现多节点通信,结合梯形加减速算法和同步控制策略,有效解决了工业自动化中多电机同步性差的问题。文章涵盖硬件设计、通信协议、抗干扰措施及实战调试经验,为工业应用提供高可靠性解决方案。

tech5的博客 978

C#中处理读写Ini文件

1、C#读写ini文件其实并不是普通的文本文件,有自己的结构。由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如: [Section1]      KeyWord1 = Value1      KeyWord2 = Value2      ...  [Section2]      Key

Mihoke的博客 3841

Material Studio 2024安装避坑指南:从证书配置到权限设置的完整解决方案

本文详细解析了Material Studio 2024的安装流程,从环境准备到权限优化的完整解决方案。针对证书配置、系统权限和计算服务等常见问题,提供了12个关键风险点的避坑指南,帮助科研工作者高效完成安装,提升材料模拟工作的效率。

moon9的博客 785

c#读写ini文件

<br />INI文件就是扩展名为"ini"的文件。<br />  其一般形式如下:<br />  [section1] // 配置节<br />  //键名 //键值<br />  keyword1 = valuel<br />  keyword2 = value2<br />  ……<br />  [section2]<br />  keyword3 = value3<br />  keyword4 = value4<br />  在Windows系统中,INI文件是很多,最重要的就是"System.i

烟逝爱情的专栏 867

手把手教你用组态王KingSCADA 3.53读取S7-1200 PLC数据(保姆级图文教程)

本文提供了一份详细的组态王KingSCADA 3.53读取S7-1200 PLC数据的实战教程,涵盖从硬件连接到软件配置、变量映射到故障排查的全流程。特别针对初学者常见问题提供解决方案,帮助工程师快速实现稳定通信,提升工业自动化系统效率。

weixin_26876073的博客 692

《低功耗方法学》翻译——第一章:介绍

第一章:介绍

记录所学,分享知识,结识挚友 2075

C# 读写ini配置文件

C# 读写ini配置文件 一、简述 记--c#通过调用系统api接口进行简单读写ini配置文件。 例子打包:外链:https://wwa.lanzoui.com/b0c9nm3pa密码:8maq 二、效果 三、工程结构 四、源代码 Program.cs文件 using System; using System.IO; namespace Configure { ...

Genven_Liang的博客 5548

2023年高教社杯全国大学生数学建模竞赛 E 题:《黄河水沙监测数据分析》真题解析与 MATLAB 解决方案

🏆 本文已收录于专栏:《滚雪球学数学建模(含历年真题)》,持续更新最新及历年数学建模竞赛资料,每篇内容力求做到“问题讲透、模型讲清、代码可用、论文可参考”,帮助你从零开始逐步建立完整的数学建模知识体系。

**My Coding Family** 911

C#中读写INI文件总结

此为公司一前辈总结的,在此感谢,就不说名儿了。一、        C#中读写INI文件方法总结:INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)  [Section]  Key=Value因为c#自己没有定义相应的方法, VC定义了API函数来读写INI文件,所以我们可以通过定义API 函数来实现读

Sugar_Tiger[糖伯虎]的专栏 2029

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C# 读写ini文件

关于C# 如何读写ini 文件 什么是ini文件,ini文件的组成结构如下: 即由section(图中Gain Info)节点名称,KEY(图中G1 Gain)和Value(等号后的数值组成)。一般作为程序的配置文件。 C# 通过调用两个系统API函数就可以进行对ini文件的读写。 首先要引用using System.Runtime.InteropServices; [DllImport(“ker...

呢小白的博客 252

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

C#如何读写和创建INI文件

在做项目过程中,有时需要保存一些简单的配置信息,可以使用xml,也可以使用INI文件。下面是C#中读取INI的方法,相信大部分朋友都使用过这种方式。 INI文件的存储方式如下, [section] key=value key=value 读取写入方法, [DllImport("kernel32")] private static extern long

杨友山 7万+

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

C# INI配置文件的读写

initialization file的缩写,即初始化文件,通常存放的是一个程序的初始化信息,是Windows的系统配置文件所采用的存储格式,统管windows的各项配置。ini文件的后缀名不一定是.ini,也可以是.cfg、.conf、或者是.tx*。:最基本元素,包含参数名(name)和参数值(value),号后直到行尾均为注释。组成,每个 key 可以赋相应的值。:所有的参数以节为单位结合在一起。组成,每个section由若干。,而这只要借助几个函数即可完成。

weixin_65414269的博客 4355
上一篇: 写一个通用数据访问组件
下一篇: 三层结构简单概述
BlueTzar
博客等级 码龄22年 10粉丝 35原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值