如何从文本文件中完成aspx连接字符串

时间:2016-12-15 14:58:05

标签: c# sql-server c#-2.0

我必须使用文本文件" db.txt"它继承了服务器和数据库的名称,以使我的连接字符串完整。

db.txt看起来像这样:

<Anfang>
SERVER==dbServer\SQLEXPRESS
DATABASE==studentweb
<Ende>

连接字符串:

string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;

不幸的是,我们只允许使用Classic ASPX.net(C#2.0)而不是web.config。 我经常搜索,但没有找到任何帮助我。 有人知道如何让它发挥作用?

1 个答案:

答案 0 :(得分:0)

这是让你前进的东西。 简而言之,我将DBInfo文件放在一个逐行读取文件的方法中。当我看到行areWeThereYet时,我知道下一行很重要,当我看到行isItDoneYet时,我知道它就结束了,所以我需要抓住它们之间的所有内容。因此,为什么我想出了我用来开始和停止从文件中收集数据的布尔Dictionary<string, string> using System; using System.Collections.Generic; namespace _41167195 { class Program { static void Main(string[] args) { string pathToDBINfoFile = @"M:\StackOverflowQuestionsAndAnswers\41167195\41167195\sample\DBInfo.txt";//the path to the file holding the info Dictionary<string, string> connStringValues = DoIt(pathToDBINfoFile);//Get the values from the file using a method that returns a dictionary string serverValue = connStringValues["SERVER"];//just for you to see what the results are string dbValue = connStringValues["DATABASE"];//just for you to see what the results are //Now you can adjust the line below using the stuff you got from above. //string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString; } private static Dictionary<string, string> DoIt(string incomingDBInfoPath) { Dictionary<string, string> retVal = new Dictionary<string, string>();//initialize a dictionary, this will be our return value using (System.IO.StreamReader sr = new System.IO.StreamReader(incomingDBInfoPath)) { string currentLine = string.Empty; bool areWeThereYet = false; bool isItDoneYet = false; while ((currentLine = sr.ReadLine()) != null)//while there is something to read { if (currentLine.ToLower() == "<anfang>") { areWeThereYet = true; continue;//force the while to go into the next iteration } else if (currentLine.ToLower() == "<ende>") { isItDoneYet = true; } if (areWeThereYet && !isItDoneYet) { string[] bleh = currentLine.Split(new string[] { "==" }, StringSplitOptions.RemoveEmptyEntries); retVal.Add(bleh[0], bleh[1]);//add the value to the dictionary } else if (isItDoneYet) { break;//we are done, get out of here } else { continue;//we don't need this line } } } return retVal; } } }

在此代码段中,我使用{{1}}来存储和返回值,但您可以使用不同的内容。起初我打算创建一个包含所有数据库信息的自定义类,但由于这是一项学校作业,我们将逐步进行,并开始使用已有的数据。

{{1}}