我用C#.NET做了一个工程,该工程包含一个web项目和一个windows项目, 现在我在一个公用类里写了他们的数据库连接字符串. 但是现在项目要求该连接字符串不能写死了,必须从一个用户可修改的文本文件里读取. 我没有做过这个,希望大家指教一下
多谢了比如说,该文本为 dbcon.txt,里面的内容包含 initial catalog = northwind
                                         user id=  sa
                                         pasword= 123456
然后我在程序里取到这些字符串.

解决方案 »

  1.   

    为什么不用config文件???
    对web项目,默认是web.config
    对于windows项目,默认是app.config
    他们的内容相同不就好了?或者只写一个config,在另外一个程序中根据路径去读取?
      

  2.   

    添加新项,选择utility,添加应用程序配置文件
      

  3.   

    要文本也可以,封装一个读这种txt的类不就好了?public class EqualFile
    {
    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();
      

  4.   

    我找到一个方法了,可以供大家分享
    .....
    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