c#读取Config文件的问题

c#读取Config文件的问题,第1张

应用程序配置文件(App.config)是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。

对于一个config文件:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="ServerIP" value="127.0.0.1"></add>

<add key="DataBase" value="WarehouseDB"></add>

<add key="user" value="sa"></add>

<add key="password" value="sa"></add>

</appSettings>

</configuration>

对config配置文件的读写类:

using System

using System.Collections.Generic

using System.Linq

using System.Text

using System.Text.RegularExpressions

using System.Configuration

using System.ServiceModel

using System.ServiceModel.Configuration

namespace NetUtilityLib

{

public static class ConfigHelper

{

//依据连接串名字connectionName返回数据连接字符串

public static string GetConnectionStringsConfig(string connectionName)

{

//指定config文件读取

string file = System.Windows.Forms.Application.ExecutablePath

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file)

string connectionString =

config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString()

return connectionString

}

///<summary>

///更新连接字符串

///</summary>

///<param name="newName">连接字符串名称</param>

///<param name="newConString">连接字符串内容</param>

///<param name="newProviderName">数据提供程序名称</param>

public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)

{

//指定config文件读取

string file = System.Windows.Forms.Application.ExecutablePath

Configuration config = ConfigurationManager.OpenExeConfiguration(file)

bool exist = false//记录该连接串是否已经存在

//如果要更改的连接串已经存在

if (config.ConnectionStrings.ConnectionStrings[newName] != null)

{

exist = true

}

// 如果连接串已存在,首先删除它

if (exist)

{

config.ConnectionStrings.ConnectionStrings.Remove(newName)

}

//新建一个连接字符串实例

ConnectionStringSettings mySettings =

new ConnectionStringSettings(newName, newConString, newProviderName)

// 将新的连接串添加到配置文件中.

config.ConnectionStrings.ConnectionStrings.Add(mySettings)

// 保存对配置文件所作的更改

config.Save(ConfigurationSaveMode.Modified)

// 强制重新载入配置文件的ConnectionStrings配置节

ConfigurationManager.RefreshSection("ConnectionStrings")

}

///<summary>

///返回*.exe.config文件中appSettings配置节的value项

///</summary>

///<param name="strKey"></param>

///<returns></returns>

public static string GetAppConfig(string strKey)

{

string file = System.Windows.Forms.Application.ExecutablePath

Configuration config = ConfigurationManager.OpenExeConfiguration(file)

foreach (string key in config.AppSettings.Settings.AllKeys)

{

if (key == strKey)

{

return config.AppSettings.Settings[strKey].Value.ToString()

}

}

return null

}

///<summary>

///在*.exe.config文件中appSettings配置节增加一对键值对

///</summary>

///<param name="newKey"></param>

///<param name="newValue"></param>

public static void UpdateAppConfig(string newKey, string newValue)

{

string file = System.Windows.Forms.Application.ExecutablePath

Configuration config = ConfigurationManager.OpenExeConfiguration(file)

bool exist = false

foreach (string key in config.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地址

public static void UpdateServiceModelConfig(string configPath, string serverIP)

{

Configuration config = ConfigurationManager.OpenExeConfiguration(configPath)

ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"]

ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup

ClientSection clientSection = serviceModelSectionGroup.Client

foreach (ChannelEndpointElement item in clientSection.Endpoints)

{

string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

string address = item.Address.ToString()

string replacement = string.Format("{0}", serverIP)

address = Regex.Replace(address, pattern, replacement)

item.Address = new Uri(address)

}

config.Save(ConfigurationSaveMode.Modified)

ConfigurationManager.RefreshSection("system.serviceModel")

}

// 修改applicationSettings中App.Properties.Settings中服务的IP地址

public static void UpdateConfig(string configPath, string serverIP)

{

Configuration config = ConfigurationManager.OpenExeConfiguration(configPath)

ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"]

ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"]

ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection

if (clientSettingsSection != null)

{

SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS")

if (element1 != null)

{

clientSettingsSection.Settings.Remove(element1)

string oldValue = element1.Value.ValueXml.InnerXml

element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP)

clientSettingsSection.Settings.Add(element1)

}

SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS")

if (element2 != null)

{

clientSettingsSection.Settings.Remove(element2)

string oldValue = element2.Value.ValueXml.InnerXml

element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP)

clientSettingsSection.Settings.Add(element2)

}

}

config.Save(ConfigurationSaveMode.Modified)

ConfigurationManager.RefreshSection("applicationSettings")

}

private static string GetNewIP(string oldValue, string serverIP)

{

string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

string replacement = string.Format("{0}", serverIP)

string newvalue = Regex.Replace(oldValue, pattern, replacement)

return newvalue

}

}

}

测试代码如下:

class Program

{

static void Main(string[] args)

{

try

{

//string file = System.Windows.Forms.Application.ExecutablePath + ".config"

//string file1 = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

string serverIP = ConfigHelper.GetAppConfig("ServerIP")

string db = ConfigHelper.GetAppConfig("DataBase")

string user = ConfigHelper.GetAppConfig("user")

string password = ConfigHelper.GetAppConfig("password")

Console.WriteLine(serverIP)

Console.WriteLine(db)

Console.WriteLine(user)

Console.WriteLine(password)

ConfigHelper.UpdateAppConfig("ServerIP", "192.168.1.11")

string newIP = ConfigHelper.GetAppConfig("ServerIP")

Console.WriteLine(newIP)

Console.ReadKey()

}

catch (Exception ex)

{

Console.WriteLine(ex.Message)

}

}

}

C#使用csc.exe编译程序,csc使用/target:library(缩写: /t:library)参数生成Dll文件。

其它参数如下:

Visual C# 编译器选项

- 输出文件 -

/out:<文件> 指定输出文件名(默认值: 包含主类的文件或第一个文件的基名称)

/target:exe生成控制台可执行文件(默认) (缩写: /t:exe)

/target:winexe 生成 Windows 可执行文件 (缩写: /t:winexe)

/target:library生成库 (缩写: /t:library)

/target:module 生成能添加到其他程序集的模块 (缩写: /t:module)

/target:appcontainerexe生成 Appcontainer 可执行文件 (缩写: /t:appcontainerexe)

/target:winmdobj 生成 WinMDExp 使用的 Windows 运行时中间文件 (缩写: /t:winmdobj)

/doc:<文件> 要生成的 XML 文档文件

/platform:<字符串>限制可以在其上运行此代码的平台: x86、Itanium、x64、arm、anycpu32bitpreferred 或 anycpu。默认值为 anycpu。

- 输入文件 -

/recurse:<通配符> 根据通配符规范,包括当前目录和子目录下的所有文件

/reference:<别名>=<文件> 使用给定的别名从指定的程序集文件引用元数据 (缩写: /r)

/reference:<文件列表> 从指定的程序集文件引用元数据 (缩写: /r)

/addmodule:<文件列表> 将指定的模块链接到此程序集中

/link:<文件列表> 嵌入指定的互 *** 作程序集文件中的元数据 (缩写: /l)

- 资源 -

/win32res:<文件> 指定 Win32 资源文件(.res)

/win32icon:<文件> 对输出使用此图标

/win32manifest:<文件> 指定 Win32 清单文件(.xml)

/nowin32manifest 不包括默认 Win32 清单

/resource:<资源信息> 嵌入指定的资源 (缩写: /res)

/linkresource:<资源信息> 将指定的资源链接到此程序集 (缩写: /linkres)

其中 resinfo 的格式是 <file>[,<string name>[,public|private]]

- 代码生成 -

/debug[+|-]发出调试信息

/debug:{full|pdbonly} 指定调试类型(“full”是默认类型,可以将调试程序附加到正在运行的程序)

/optimize[+|-] 启用优化 (缩写: /o)

- 错误和警告 -

/warnaserror[+|-] 将所有警告报告为错误

/warnaserror[+|-]:<警告列表> 将特定警告报告为错误

/warn:<n> 设置警告等级(0-4) (缩写: /w)

/nowarn:<警告列表>禁用特定的警告消息

- 语言 -

/checked[+|-] 生成溢出检查

/unsafe[+|-] 允许“不安全”代码

/define:<符号列表>定义条件编译符号 (缩写: /d)

/langversion:<字符串> 指定语言版本模式: ISO-1、ISO-2、3、4、5 或 Default

- 安全性 -

/delaysign[+|-]仅使用强名称密钥的公共部分对程序集进行延迟签名

/keyfile:<文件> 指定强名称密钥文件

/keycontainer:<字符串>指定强名称密钥容器

/highentropyva[+|-]启用高平均信息量的 ASLR

- 杂项 -

@<文件> 有关更多选项,请阅读响应文件

/help 显示此用法信息 (缩写: /?)

/nologo取消编译器版权信息

/noconfig 不要自动包含 CSC.RSP 文件

- 高级 -

/baseaddress:<地址> 要生成的库的基址

/bugreport:<文件> 创建“Bug 报告”文件

/codepage:<n> 指定打开源文件时要使用的代码页

/utf8output以 UTF-8 编码格式输出编译器消息

/main:<类型> 指定包含入口点的类型(忽略所有其他可能的入口点) (缩写: /m)

/fullpaths 编译器生成完全限定路径

/filealign:<n>指定用于输出文件节的对齐方式

/pdb:<文件> 指定调试信息文件名(默认值: 扩展名为 .pdb 的输出文件名)

/errorendlocation 输出每个错误的结束位置的行和列

/preferreduilang 指定首选输出语言名称。

/nostdlib[+|-] 不引用标准库(mscorlib.dll)

/subsystemversion:<字符串>指定此程序集的子系统版本

/lib:<文件列表> 指定要在其中搜索引用的附加目录

/errorreport:<字符串> 指定如何处理内部编译器错误: prompt、send、queue 或 none。默认值为 queue。

/appconfig:<文件> 指定一个包含程序集绑定设置的应用程序配置文件

/moduleassemblyname:<字符串> 此模块所属程序集的名称

都可以的

就纯单元文件而言(不是窗体的pas)

举例

unit Global

interface

uses

Windows,Forms,Dialogs,SysUtils,DB, ADODB

Function Connection:Integer //申明一个连接数据库函数

var

AppConfig:TIniFile//配置文件读 0写对象

implementation

function readconfig:boolean

begin

读取数据库配置文件

end

Function Connection:Integer // 连接数据库函数的具体实现

Begin

if readconfig then

begin

连接数据库代码

end

else

begin

showmessage('读取配置文件失败')

end

end、

里面有2个函数 Connection就是在type下 readconfig就是在implementation下

区别就是Connection这样申明可以被其他单元条用 而 readconfig就只能被它下面的代码和函数条用。

因为这个是纯pas文件 所以没有{$R *.dfm}

如果是在窗体的pas里

unit Unit1

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs

type

TForm1 = class(TForm)

procedure FormCreate(Sender: TObject)

private

私有函数可以声明在这儿 只能被本pas调用

public

公有函数可以声明在这儿 可以被其他pas调用

end

var

Form1: TForm1

implementation

{$R *.dfm}

局部函数可以声明在这儿。可以被以下的函数调用

以上说明2种pas 调用方式 前者只要引用pas 然后直接执行Connection即可

而后者因为函数式属于TForm1 这个类下面的 所以调用要引用这个单元文件后

执行 Form1.函数名 例如 form1.sss

另外还可以在函数内部再声明函数‘

例如 过程sss内部还有个getid函数 只能被sss里面的代码调用

procedure TForm1.sss

function getid:integer

begin

result:=111

end

var

k:integer

begin

k:=1

showmessage(inttostr(getid+k))

end


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/6787572.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-28
下一篇 2023-03-28

发表评论

登录后才能评论

评论列表(0条)

保存