程序是怎样读写配置文件的|java如何读取XML配置文件

|

Ⅰ 如何在C#控制台程序中读取配置文件中的信息

给个例子你:配置文件App.config如下:<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="InvariantInfo" value="true"/> </appSettings></configuration>使用if (ConfigurationManager.AppSettings["InvariantInfo"] != "false"){} 绝对没问题的,我都取过N遍了,不行你把你的配置文件删除了,再到VS里面添加一个app.config文件,把内容复制过来 我是用的VS,用CSC编译可能是少了参数了你

Ⅱ java如何读取XML配置文件

JAVA与XML文件,可以说是软件开发的“黄金搭档”,而如何使用JAVA完成对文件的读取,是我们首先要解决的问题。一、XML文件这个示例文件包括了用来打开ORACLE数据库的各种参数<?xml version="1.0" encoding="UTF-8"?><dbmsg> <dbinfo> <drivername>oracle.jdbc.driver.OracleDriver</drivername> <sConnStr>jdbc:oracle:thin:@11.88.225.80:1521:VOUCHERDB</sConnStr> <username>SYS AS SYSDBA</username> <password>voucherdb</password> </dbinfo></dbmsg>二、编写类名为ReadXml的类,用于解析XML文件我们要在应用程序中打开数据库,就必须完成对该文件中drivername、sConnStr、username、password的读取,通过查找有关资料,笔者编制了以下程序,用于读取文件名为filename的XML文件。package voucher.basic;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class ReadXml { private String drivername; private String sConnStr; private String username; private String password; public String getDrivername() { return drivername; }public String getSConnStr() { return sConnStr; }public String getUsername() { return username; }public String getPassword() { return password; } public void setDrivername(String drivername) { this.drivername = drivername; }public void setSConnStr(String connStr) { sConnStr = connStr; }public void setUsername(String username) { this.username = username; }public void setPassword(String password) { this.password = password; }public ReadXml(String fileName){ DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance(); try { DocumentBuilder dombuilder=domfac.newDocumentBuilder(); InputStream is=new FileInputStream(fileName); Document doc=dombuilder.parse(is); Element root=doc.getDocumentElement(); NodeList dbinfo=root.getChildNodes(); if(dbinfo!=null){ for(int i=0;i<dbinfo.getLength();i++){ Node db=dbinfo.item(i); for(Node node=db.getFirstChild();node!=null;node=node.getNextSibling()){ if(node.getNodeType()==Node.ELEMENT_NODE){ if(node.getNodeName().equals("drivername")){ setDrivername(node.getFirstChild().getNodeValue()); } if(node.getNodeName().equals("sConnStr")){ setSConnStr(node.getFirstChild().getNodeValue()); } if(node.getNodeName().equals("username")){ setUsername(node.getFirstChild().getNodeValue()); } if(node.getNodeName().equals("password")){ setPassword(node.getFirstChild().getNodeValue()); } } } } } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }这个以ReadXml命名的类,使用了参数为文件名的构造方法,用户只要将配置文件我名称传递给该方法,就可以完成对XML文件的解析,进而完成对相应参数数的读取。三、如何获取XML文件全路径并读取配置参数获取XML文件全路径的方法有两个,一是在servlet中获取,二是在单独的JAVA类中获取。1.在servlet中获取XML文件的全路径并读取配置参数程序片段String dirPath = getServletContext().getRealPath( "/WEB-INF"); String fileName = dirPath + "/conn.xml"; ReadXml xm = new ReadXml(fileName); String DriverName = xm.getDrivername(); String connStr = xm.getSConnStr(); String user = xm.getUsername(); String pas = xm.getPassword();将这段程序添加到servlet中dopost()之后即可完成参数的读取2.在单独的JAVA类中获取全路径并读取配置参数程序片段String dirpath = System.getProperty("user.dir"); String xmlFile = dirpath + "/WebRoot/WEB-INF/conn.xml"; ReadXml rdxml = new ReadXml(xmlFile); String driverName = rdxml.getDrivername(); String sConnStr = rdxml.getSConnStr(); String userName = rdxml.getUsername(); String passWord = rdxml.getPassword();注:配置文件conn.xml保存在webroot/WEB-INF目录中。

Ⅲ C#如何读取config配置文件数据

代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Configuration;usingSystem.ServiceModel;usingSystem.ServiceModel.Configuration;namespaceNetUtilityLib{publicstaticclassConfigHelper{//依据连接串名字connectionName返回数据连接字符串(stringconnectionName){//指定config文件读取stringfile=System.Windows.Forms.Application.ExecutablePath;System.Configuration.Configurationconfig=ConfigurationManager.OpenExeConfiguration(file);stringconnectionString=config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();returnconnectionString;}///<summary>///更新连接字符串///</summary>///<paramname="newName">连接字符串名称</param>///<paramname="newConString">连接字符串内容</param>///<paramname="newProviderName">数据提供程序名称</param>(stringnewName,stringnewConString,stringnewProviderName){//指定config文件读取stringfile=System.Windows.Forms.Application.ExecutablePath;Configurationconfig=ConfigurationManager.OpenExeConfiguration(file);boolexist=false;//记录该连接串是否已经存在//如果要更改的连接串已经存在if(config.ConnectionStrings.ConnectionStrings[newName]!=null){exist=true;}//如果连接串已存在,首先删除它if(exist){config.ConnectionStrings.ConnectionStrings.Remove(newName);}//新建一个连接字符串实例=newConnectionStringSettings(newName,newConString,newProviderName);//将新的连接串添加到配置文件中.config.ConnectionStrings.ConnectionStrings.Add(mySettings);//保存对配置文件所作的更改config.Save(ConfigurationSaveMode.Modified);//强制重新载入配置文件的ConnectionStrings配置节ConfigurationManager.RefreshSection("ConnectionStrings");}///<summary>///返回*.exe.config文件中appSettings配置节的value项///</summary>///<paramname="strKey"></param>///<returns></returns>(stringstrKey){stringfile=System.Windows.Forms.Application.ExecutablePath;Configurationconfig=ConfigurationManager.OpenExeConfiguration(file);foreach(stringkeyinconfig.AppSettings.Settings.AllKeys){if(key==strKey){returnconfig.AppSettings.Settings[strKey].Value.ToString();}}returnnull;}///<summary>///在*.exe.config文件中appSettings配置节增加一对键值对///</summary>///<paramname="newKey"></param>///<paramname="newValue"></param>(stringnewKey,stringnewValue){stringfile=System.Windows.Forms.Application.ExecutablePath;Configurationconfig=ConfigurationManager.OpenExeConfiguration(file);boolexist=false;foreach(stringkeyinconfig.AppSettings.Settings.AllKeys){if(key==newKey){exist=true;}}if(exist){config.AppSettings.Settings.Remove(newKey);}config.AppSettings.Settings.Add(newKey,newValue);config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("appSettings");}//修改system.serviceModel下所有服务终结点的IP地址(stringconfigPath,stringserverIP){Configurationconfig=ConfigurationManager.OpenExeConfiguration(configPath);ConfigurationSectionGroupsec=config.SectionGroups["system.serviceModel"];=secasServiceModelSectionGroup;ClientSectionclientSection=serviceModelSectionGroup.Client;foreach(.Endpoints){[email protected]"d{1,3}.d{1,3}.d{1,3}.d{1,3}";stringaddress=item.Address.ToString();stringreplacement=string.Format("{0}",serverIP);address=Regex.Replace(address,pattern,replacement);item.Address=newUri(address);}config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("system.serviceModel");}//修改applicationSettings中App.Properties.Settings中服务的IP地址publicstaticvoidUpdateConfig(stringconfigPath,stringserverIP){Configurationconfig=ConfigurationManager.OpenExeConfiguration(configPath);ConfigurationSectionGroupsec=config.SectionGroups["applicationSettings"];=sec.Sections["DataService.Properties.Settings"];=;if(clientSettingsSection!=null){SettingElementelement1=clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS");if(element1!=null){clientSettingsSection.Settings.Remove(element1);stringoldValue=element1.Value.ValueXml.InnerXml;element1.Value.ValueXml.InnerXml=GetNewIP(oldValue,serverIP);clientSettingsSection.Settings.Add(element1);}SettingElementelement2=clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS");if(element2!=null){clientSettingsSection.Settings.Remove(element2);stringoldValue=element2.Value.ValueXml.InnerXml;element2.Value.ValueXml.InnerXml=GetNewIP(oldValue,serverIP);clientSettingsSection.Settings.Add(element2);}}config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("applicationSettings");}privatestaticstringGetNewIP(stringoldValue,stringserverIP){[email protected]"d{1,3}.d{1,3}.d{1,3}.d{1,3}";stringreplacement=string.Format("{0}",serverIP);stringnewvalue=Regex.Replace(oldValue,pattern,replacement);returnnewvalue;}}}

Ⅳ 易语言如何读写配置文件,

我不要分帮你,采纳让我采纳率提高,谢谢!写个 例子给你.版本 2.程序集 窗口程序集1.程序集变量 程序集变量_x, 文本型.程序集变量 程序集变量_y, 文本型.程序集变量 程序集变量_Word, 文本型.子程序 _按钮1_被单击' 比如个按钮写配置项 或 你自定义其他方式去写写配置项 (取运行目录 () + “\system.ini”, “Coordinates”, “x”, “100”)写配置项 (取运行目录 () + “\system.ini”, “Coordinates”, “y”, “100”)写配置项 (取运行目录 () + “\system.ini”, “Text”, “Word”, “字”).子程序 __启动窗口_创建完毕程序集变量_x = 读配置项 (取运行目录 () + “\system.ini”, “Coordinates”, “x”, )程序集变量_y = 读配置项 (取运行目录 () + “\system.ini”, “Coordinates”, “y”, )程序集变量_Word = 读配置项 (取运行目录 () + “\system.ini”, “Text”, “Word”, )' 然后把程序集变量or 全局变量 赋值到你的子程序变量中子程序1 ().子程序 子程序1.局部变量 横坐标存, 整数型.局部变量 横坐标, 整数型.局部变量 纵坐标, 整数型.局部变量 字, 文本型.局部变量 字存, 文本型.局部变量 纵坐标存, 整数型' 例如横坐标 = 到整数 (程序集变量_x)纵坐标 = 到整数 (程序集变量_y)字 = 程序集变量_Word

Ⅳ Qt如何读取配置文件

我写个了程序,用到了配置文件来初始化和保存程序中的文本框的信息内。在我的电脑可以实现 但是容发到不装Qt的电脑上,程序就只可以读取配置文件的数据 , 但是不能把新信息写入。——解决方案————————————————————–解决方案——————————————————–没qt的电脑,需要你把自己exe依赖的qt库都打包放在一起,这样在没qt环境的电脑上才能正常运行。——解决方案——————————————————–

Ⅵ 如何使用Python3读写INI配置文件

ini文件简介ini是我们常见到的配置文件格式之一。ini是微软Windows操作系统中的文件扩展名(也常用在其他系统)。INI是英文“初始化(Initial)”的缩写。正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。网络通过它,可以将经常需要改变的参数保存起来(而且还可读),使程序更加的灵活。我先给出一个ini文件的示例。[School]ip = 10.15.40.123mask = 255.255.255.0gateway = 10.15.40.1dns = 211.82.96.1[Match]ip = 172.17.29.120mask = 255.255.255.0gateway = 172.17.29.1dns = 0.0.0.0这个配置文件中保存的是不同场合下的IP设置参数。下面将以生成和读取这个配置文件为例,进行讲解。Python(v3)读取方法首先,Python读取ini配置需要用到ConfigParser包,所以要先加载它。import configparser之后我们需要载入配置文件。config=configparser.ConfigParser()#IpConfig.ini可以是一个不存在的文件,意味着准备新建配置文件。config.read("IpConfig.ini")接下来,我们可以使用configparser.add_section()向配置文件中添加一个Section。#添加节Schoolconfig.add_section("School")注意:如果文件中已经存在相应的项目,则不能再增加同名的节。然后可以使用configparser.set()在节School中增加新的参数。#添加新的IP地址参数config.set("School","IP","192.168.1.120")config.set("School","Mask","255.255.255.0")config.set("School","Gateway","192.168.1.1")config.set("School","DNS","211.82.96.1")你可以以同样的方式增加其它几项。#由于ini文件中可能有同名项,所以做了异常处理try:config.add_section("Match")config.set("Match","IP","172.17.29.120")config.set("Match","Mask","255.255.255.0")config.set("Match","Gateway","172.17.29.1")config.set("Match","DNS","0.0.0.0")except configparser.DuplicateSectionError:print("Section 'Match' already exists")增加完所有需要的项目后,要记得使用configparser.write()进行写入操作。config.write(open("IpConfig.ini", "w"))以上就是写入配置文件的过程。接下来我们使用configparser.get()读取刚才写入配置文件中的参数。读取之前要记得读取ini文件。ip=config.get("School","IP")mask=config.get("School","mask")gateway=config.get("School","Gateway")dns=config.get("School","DNS")print((ip,mask+"\n"+gateway,dns))完整示例下面是一个完整的示例程序,他将生成一个IpConfig.ini的配置文件,再读取文件中的数据,输出到屏幕上。# -*- coding: utf-8 -*-import configparser#读取配置文件config=configparser.ConfigParser()config.read("IpConfig.ini")#写入宿舍配置文件try:config.add_section("School")config.set("School","IP","10.15.40.123")config.set("School","Mask","255.255.255.0")config.set("School","Gateway","10.15.40.1")config.set("School","DNS","211.82.96.1")except configparser.DuplicateSectionError:print("Section 'School' already exists")#写入比赛配置文件try:config.add_section("Match")config.set("Match","IP","172.17.29.120")config.set("Match","Mask","255.255.255.0")config.set("Match","Gateway","172.17.29.1")config.set("Match","DNS","0.0.0.0")except configparser.DuplicateSectionError:print("Section 'Match' already exists")#写入配置文件config.write(open("IpConfig.ini", "w"))ip=config.get("School","IP")mask=config.get("School","mask")gateway=config.get("School","Gateway")dns=config.get("School","DNS")print((ip,mask+"\n"+gateway,dns))总结Python读取ini文件还是十分简单的,这里我给出的只是一些简单的使用方法,如果想用更高级的功能,比如和注释有关的功能。可以参考Pyhton官方文档

Ⅶ 如何用VB读取ini配置文件

为了方便用户使用和使系统具有灵活性,大多数Win-dows应用程序将用户所做的选择以及各种变化的系统信息记录在初始化(INI)文件中。因此,当系统的环境发生变化时,可以直接修改INI文件,而无需修改程序。由此可见,INI文件对系统功能是至关重要的。本文将介绍采用VisualBasicforWindows(下称VB)开发Windows应用程序时如何读写INI文件。INI文件是文本文件,由若干部分(section)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键词(keyword)和一个等号,每个关键词会控制应用程序某个功能的工作方式,等号右边的值(value)指定关键词的操作方式。其一般形式如下:[section1]keyword1=valuelkeyword2=value2……[section2]keyword1=value1keyword2=value2……其中,如果等号右边无任何内容(即value为空),那就表示Windows应用程序已为该关键词指定了缺省值,如果在整个文件中找不到某个关键词(或整个一部分),那同样表示为它们指定了缺省值。各个部分所出现的顺序是无关紧要的,在每一个部分里,各个关键词的顺序同样也无关紧要。读写INI文件通常有两种方式:一是在Windows中用"记事本"(Notepad)对其进行编辑,比较简单,无需赘述;二是由Windows应用程序读写INI文件,通常是应用程序运行时读取INI文件中的信息,退出应用程序时保存用户对运行环境的某些修改。关键词的值的类型多为字符串或整数型,应分两种情况读写。为了使程序具有可维护性和可移植性,最好把对INI文件的读写封装在一个模块(RWINI.BAS)中,在RWI-NI.BAS中构造GetIniS和GetIniN函数以及SetIniS和Se-tIniN过程,在这些函数和过程中需要使用WindowsAPI的"GetPrivateprofileString"、"GetPrivateProfileInt"和"WritePrivateProfileString"函数。RWINI.BAS模块的程序代码如下:在General-Declearation部分中声明使用到的WindowsAPI函数:Declare Function GetprivateprofileString Lib"Ker-nel"(ByVallpAppName As String,ByVallpKeyName As String,ByVallpDefault As String,ByVal lpRetrm-String As String,ByVal cbReturnString As Integer,ByVal Filename As String)As IntegerDeclare FunctionGetPrivatePfileInt Lib "Kernel"(ByVal lpAppName As String,ByVal lpKeyName As String,ByVal lpDefault As Integer,ByVal Filename As String)As IntegerDeclare Lib "Kernel"(ByVal lpApplicationName As String,ByVal lpKeyName As String,ByVal lpString As String,ByVal lplFileName As String)As IntegerFunction GetIniS(ByVal SectionName As String,ByVal KeyWord As String,ByVal DefString As String)As StringDim ResultString As String * 144,Temp As IntegerDims As String,i As IntegerTemp%=GetPrivateProfileString(SectionName,KeyWord,"",ResultString,144,AppProfileName())‘检索关键词的值IfTemp%>0Then‘关键词的值不为空s=""Fori=1To144IfAsc(Mid$(ResultString,I,1))=0ThenExitForElses=s&Mid$(ResultString,I,1)EndIfNextElseTemp%=WritePrivateProfilesString(sectionname,KeyWord,DefString,ppProfileName())‘将缺省值写入INI文件s=DefStringEndIfGetIniS=sEndFunctionFunctionGetIniN(ByValSectionNameAsString,ByValKeyWordAsString,ByValDefValueAsIneger)AsIntegerDimdAsLong,sAsStringd=DefValueGetIniN=GetPrivateProfileInt(SectionName,KeyWord,DefValue,ppProfileName())Ifd<>DefValueThens=""&dd=WritePrivateProfileString(SectionName,KeyWord,s,AppProfileName())EndIfEndFunctionSubSetIniS(ByValSectionNameAsString,BtVaKeyWordAsString,ByValValStrAsString)Dimres%res%=WritePrivateprofileString(SectionName,KeyWord,ValStr,AppProfileName())EndSubSubSetIniN(ByValSectionNameAsString,ByValKeyWordAsString,ByValValIntAsInteger)Dimres%,s$s$=Str$(ValInt)res%=WriteprivateProfileString(SectionName,KeyWord,s$,AppProfileName())EndSubSectionName为每一部分的标题,KeyWord为关键词,GetIniS和GetIniN中的DefValue为关键词的缺省值,SetIniS和SetIniN的ValStr和ValInt为要写入INI文件的关键词的值。为了能更好地说明如何使用以上函数和过程,下面举两个实例。实例1:开发应用程序通常要使用数据库和其它一些文件,这些文件的目录(包括路径和文件名)不应在程序中固定,而是保存在INI文件中,程序运行时由INI文件中读入。读入数据库文件的代码如下:DimDatabasenameAsStringDatabasename=GetIniS("数据库","职工","")IfDatabaseName=""ThenDatabaseName=InputBox("请输入数据库《职工》的目录"),App.Title)’也可通过"文件对话框"进行选择OnErrorResumeNextSetdb=OpenDatabas(DatabaseName)IfErr<>0ThenMsgBox"打开数据库失败!",MB-ICONSTOP,App.Title:GotoErrorProcessingElseSetIniS"数据库","职工",DatabaseNameEndIfOnErrorGoTo0……实例2:为了方便用户操作,有时需要保存用户界面的某些信息,例如窗口的高度和宽度等。装载窗体时,从INI文件中读入窗体高度和宽度,卸载窗体时将窗体当前高度和宽度存入INI文件,代码如下:Sub Form1_Load()……Forml.Height=GetIniN("窗体1","高度",6000)Form1.Width=GetIniN("窗体1","高度",4500)EndSub……Sub Form1_Unload()……SetIniN"窗体1","高度",Me.HeightSetIniN"窗体1,"宽度",Me.Width……End Sub

Ⅷ 用C#如何读写配置文件

INI文件就是扩展名为"ini"的文件。其一般形式如下:[section1] // 配置节//键名 //键值keyword1 = valuelkeyword2 = value2……[section2]keyword3 = value3keyword4 = value4在Windows系统中,INI文件是很多,最重要的就是"System.ini"、"System32.ini"和"Win.ini"。该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。以及XML文件的国际标准化给INI文件又一次打击。但在某些场合,INI文件还拥有其不可替代的地位。比如绿色软件的规定就是不向注册表和系统中填入新东西。对于软件需要储存的信息就需要存入到文件中了。XML虽然兼容性比较好,但对于仅仅保存几个自定义参数而言就显得大材小用了。这是就可以选择使用快速简单的储存方式:INI文件。本文就来探讨一下C#是如何对INI进行读写操作。主要思路是调用Win32 API。1.引入命名空间usingSystem.Runtime.InteropServices;2.声明(把一个Win32 API函数转成C#函数)//声明INI文件的写操作函数 WritePrivateProfileString()[DllImport("kernel32")]private static extern longWritePrivateProfileString(string section, string key, string val, stringfilePath);//声明INI文件的读操作函数 GetPrivateProfileString()[DllImport("kernel32")]private static extern intGetPrivateProfileString(string section, string key, string def, StringBuilderretVal, int size, string filePath);3.函数public void Writue(string section,string key, string value){// section=配置节,key=键名,value=键值,path=路径WritePrivateProfileString(section,key, value, sPath);}public string ReadValue(stringsection, string key){// 每次从ini中读取多少字节System.Text.StringBuilder temp =new System.Text.StringBuilder(255);// section=配置节,key=键名,temp=上面,path=路径GetPrivateProfileString(section,key, "", temp, 255, sPath);returntemp.ToString(); //注意类型的转换}到此基本功能已经实现了。下面我们将所有的代码重新整合一下:namespace Library.File{public class Ini{// 声明INI文件的写操作函数 WritePrivateProfileString()[System.Runtime.InteropServices.DllImport("kernel32")]private static extern longWritePrivateProfileString(string section, string key, string val, stringfilePath);// 声明INI文件的读操作函数 GetPrivateProfileString()[System.Runtime.InteropServices.DllImport("kernel32")]private static extern intGetPrivateProfileString(string section, string key, string def,System.Text.StringBuilder retVal, int size, string filePath);private string sPath = null;public Ini(string path){this.sPath = path;}public void Writue(string section,string key, string value){// section=配置节,key=键名,value=键值,path=路径WritePrivateProfileString(section,key, value, sPath);}public string ReadValue(stringsection, string key){// 每次从ini中读取多少字节System.Text.StringBuilder temp =new System.Text.StringBuilder(255);// section=配置节,key=键名,temp=上面,path=路径GetPrivateProfileString(section,key, "", temp, 255, sPath);return temp.ToString();}}}开始调用函数。// 写入iniIni ini = newIni("C:/config.ini");ini.Writue("Setting","key1", "HELLO WORLD!");ini.Writue("Setting","key2", "HELLO CHINA!");// 读取iniIni ini = newIni("C:/config.ini");string str1 =ini.ReadValue("Setting", "key1");MessageBox.Show(str1);二,在一些小的应用中,有时候不需要使用数据困这样大规模的数据管理工具,也很少进行数据的查询、修改等操作,而仅用文件来存储数据。这时就需要使用。net中的文件操作对象,如file、streamReader、streamWriter等。1,使用File对象操作文件System.IO.File类提供了一系类的静态办法,完成对晚间的常用操作,如新建、删除、拷贝、移动等2,使用StreamWriter写入文件在System.IO空间中定义了一个文件写入器对象StreamWriter,使用它可以以一种特定的编码向输出流中(Stream)写入字符。3,使用SteamReader读取文件与streamWrite对应

Ⅸ 如何使用Python3读取配置文件

ini是微软Windows操作系统中的文件扩展名(也常用在其他系统)。

INI是英文“初始化(Initial)”的缩写。正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。通过它,可以将经常需要改变的参数保存起来(而且还可读),使程序更加的灵活。

先给出一个ini文件的示例。

[School]ip=10.15.40.123mask=255.255.255.0gateway=10.15.40.1dns=211.82.96.1[Match]ip=172.17.29.120mask=255.255.255.0gateway=172.17.29.1dns=0.0.0.0

这个配置文件中保存的是不同场合下的IP设置参数。

首先,Python读取ini配置需要用到ConfigParser包,所以要先加载它。

importconfigparser

之后我们需要载入配置文件。

config=configparser.ConfigParser()

#IpConfig.ini可以是一个不存在的文件,意味着准备新建配置文件。

config.read("IpConfig.ini")

接下来,我们可以使用configparser.add_section()向配置文件中添加一个Section。

#添加节School

config.add_section("School")

注意:如果文件中已经存在相应的项目,则不能再增加同名的节。

然后可以使用configparser.set()在节School中增加新的参数。

#添加新的IP地址参数

config.set("School","IP","192.168.1.120")config.set("School","Mask","255.255.255.0")config.set("School","Gateway","192.168.1.1")config.set("School","DNS","211.82.96.1")

你可以以同样的方式增加其它几项。

#由于ini文件中可能有同名项,所以做了异常处理

try:config.add_section("Match")config.set("Match","IP","172.17.29.120")config.set("Match","Mask","255.255.255.0")config.set("Match","Gateway","172.17.29.1")config.set("Match","DNS","0.0.0.0")exceptconfigparser.DuplicateSectionError:print("Section'Match'alreadyexists")

增加完所有需要的项目后,要记得使用configparser.write()进行写入操作。

config.write(open("IpConfig.ini","w"))

以上就是写入配置文件的过程。

接下来我们使用configparser.get()读取刚才写入配置文件中的参数。读取之前要记得读取ini文件。

ip=config.get("School","IP")mask=config.get("School","mask")gateway=config.get("School","Gateway")dns=config.get("School","DNS")print((ip,mask+"
"+gateway,dns)

下面是一个完整的示例程序,它将生成一个IpConfig.ini的配置文件,再读取文件中的数据,输出到屏幕上。

#-*-coding:utf-8-*-importconfigparser#读取配置文件config=configparser.ConfigParser()config.read("IpConfig.ini")#写入宿舍配置文件try:config.add_section("School")config.set("School","IP","10.15.40.123")config.set("School","Mask","255.255.255.0")config.set("School","Gateway","10.15.40.1")config.set("School","DNS","211.82.96.1")exceptconfigparser.DuplicateSectionError:print("Section'School'alreadyexists")#写入比赛配置文件try:config.add_section("Match")config.set("Match","IP","172.17.29.120")config.set("Match","Mask","255.255.255.0")config.set("Match","Gateway","172.17.29.1")config.set("Match","DNS","0.0.0.0")exceptconfigparser.DuplicateSectionError:print("Section'Match'alreadyexists")#写入配置文件config.write(open("IpConfig.ini","w"))ip=config.get("School","IP")mask=config.get("School","mask")gateway=config.get("School","Gateway")dns=config.get("School","DNS")print((ip,mask+"
"+gateway,dns))

Ⅹ 怎样用VC++写个能读写配置文件的程序

本题可以使用标准的windows配置文件来做,文件名使用httpd.conf,在配置文件中Listen使用格式与要求稍有不同,为Listen= 或者Listen=8080 创建配置文件的方法 char strBuff[256]; //建立256字节的数组 CString strFilePath; //存放文件完整路径 GetCurrentDirectory(256,strBuff); //获取当前工作路径 strFilePath.Format("%s\\httpd.conf",strBuff); //配置文件完整路径 FILE *fp = fopen(strFilePath, "r"); //读配置文件,实际是测试文件是否存在 if(fp == NULL) //文件不存在 { WritePrivateProfileString("CONFIG","Listen","",strFilePath); //写Listen字段到配置文件中 } httpd.conf配置文件创建后内容如下:[CONFIG]Listen= 读取配置文件的方法 char strBuff[256]; //建立256字节的数组 CString strFilePath; //存放文件完整路径 GetCurrentDirectory(256,strBuff);//获取当前工作路径 strFilePath.Format("%s\\httpd.conf",strBuff); //配置文件路径 GetPrivateProfileString("CONFIG","Listen",NULL,strBuff,80,strFilePath); //读取ini文件中Listen字段 if (strBuff[0]==0) //字段为空 { WritePrivateProfileString("CONFIG","Listen","8080",strFilePath); //Listen字段修改为8080 } httpd.conf配置文件修改后内容如下:[CONFIG]Listen=8080 若满意请及时采纳,谢谢


赞 (0)