我用C#.NET做了一个工程,该工程包含一个web项目和一个windows项目, 现在我在一个公用类里写了他们的数据库连接字符串. 但是现在项目要求该连接字符串不能写死了,必须从一个用户可修改的文本文件里读取. 我没有做过这个,希望大家指教一下
多谢了比如说,该文本为 dbcon.txt,里面的内容包含 initial catalog = northwind
user id= sa
pasword= 123456
然后我在程序里取到这些字符串.
多谢了比如说,该文本为 dbcon.txt,里面的内容包含 initial catalog = northwind
user id= sa
pasword= 123456
然后我在程序里取到这些字符串.
解决方案 »
- C#制作自动回帖,求了很久没人会。
- .net前台数据的问题
- C# String.Format 日期
- 小键盘上 back space 的应答码是什么,程序里要捕捉这个按钮?
- DataRelation的问题
- 关于 Windows Media Player 和 RealONE Player 的问题
- Master/detail 程序的增加﹑修改﹑保存
- 谁对嵌套事务比较熟,能详细说下吗?
- MenuItem控件、ContextMenu控件???
- C#中操作PowerPoint 能不能将一个ppt中的页复制到另一个ppt中
- C# winform ListView 内容导入到xml中
- 输出时如何在小于10的数前加0?
对web项目,默认是web.config
对于windows项目,默认是app.config
他们的内容相同不就好了?或者只写一个config,在另外一个程序中根据路径去读取?
{
private StreamReader sr;
private string path; public EqualFile(string path)
{
this.path = path;
sr = new StreamReader(path, Encoding.UTF8);
} public IDictionary ReadAll()
{
string line = null;
int p = -1;
ListDictionary ld = new ListDictionary();
while( (line = sr.ReadLine()) != null)
{
line = line.TrimStart().TrimEnd();
if( line.Trim() != string.Empty && (p = line.IndexOf("="))!= -1)
{
ld.Add(line.Substring(0, p).TrimEnd(), line.Substring(p+1).TrimStart());
}
}
return ld;
} public void Close()
{
if( sr != null)
sr.Close();
}
}//class EqualFile然后如此调用:EqualFile ef = new EqualFile("c:\\test.txt");
IDictionary dic = ef.ReadAll();
ef.Close();
StringBuilder sb = new StringBuilder(512);
foreach(string key in dic.Keys)
{
sb.AppendFormat("{0}='{1}';", key, dic[key]);
}
string connectionString = sb.ToString();
.....
using System.Runtime.InteropServices; // For :[DllImport("kernel32")] private string IniFilePath ="";
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
public void Open()
{
//数据库连接初始化配置
StringBuilder val = new StringBuilder();
//string ip = "";
string db_name = "";
string username = "";
string passwd = "";
//文件保存路径
this.IniFilePath = "C:\\Inetpub\\wwwroot\\RemoteConf.ini";
try
{
GetPrivateProfileString("DBCONFIG","DBNAME","",val,30,this.IniFilePath );
db_name = val.ToString().Trim();
}
catch ( Exception ee )
{
MessageBox.Show( "获取[数据库]出错,请确认文件存在并且ip配置正确。出错信息: " + ee.Message );
}
.......
只要在相应位置建一个配置文件即可,内容格式如下:
[DBCONFIG]
IP = 127.0.0.1
DBNAME = northwind
USER = sa
PASSWD = 123456