SQL reading the connection string

时光总嘲笑我的痴心妄想 提交于 2019-12-11 09:14:52

问题


is it possible to read the connection string from a txt file, by using the direct path of the said .txt file witch containts the connection string.

The code is the following, i have this line wich i want to read the .txt file:

SqlConnection conn = @"Data Source='C:\Users\Administrator\Desktop\connstring.txt'";

Instide the said txt file is the real connection string wich is this:

@"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";

I know this might not be very safe but it's only an academical exercise, trying to learn c# and sql.


回答1:


In short: no, it is not possible to do it like this. You need an object that can read from a stream first, obtain you connection string using that reader and then pass the connection string to the constructor of your SqlConnection object instance.

string connectionString; 
var path = @"C:\Users\Administrator\Desktop\connstring.txt";
using (StreamReader sr = new StreamReader(path))
{
    connectionString = sr.ReadLine();
}

var connection = new SqlConnection(connectionString);


来源:https://stackoverflow.com/questions/31703781/sql-reading-the-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!