1

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

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

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

Inside the said txt file is the real connection string which 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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • [Look here](https://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx) –  Jul 29 '15 at 14:48
  • see here https://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx – HaveNoDisplayName Jul 29 '15 at 14:48
  • possible duplicate of [What's the fastest way to read a text file line-by-line?](http://stackoverflow.com/questions/8037070/whats-the-fastest-way-to-read-a-text-file-line-by-line) – HaveNoDisplayName Jul 29 '15 at 14:48
  • it's usually best practice to read connection strings from either the `app.config` or the `web.config` (depending if the program in question is web based or standalone). Doing so is a bit more secure than pulling the connection string from a random text file (which someone with knowledge could easily access and use for malicious purposes - especially in a web application). – user2366842 Jul 29 '15 at 15:07
  • There is built in support to read connection strings from an app.config file via ConfigurationManager.ConnectionStrings – Alex K. Jul 29 '15 at 15:28

1 Answers1

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);
Kapol
  • 6,383
  • 3
  • 21
  • 46
  • Yes this does the trick! thank for explaing so well how to do it, for someone new, it helps alot even on the most simple of things, once again thank yout. – ThatNewbieProgrammer Jul 29 '15 at 14:58
  • 1
    You could also use `string connectionString = File.ReadAllText(path);` and that's all there is to it .... – marc_s Jul 29 '15 at 15:03