C#: Need help with reading connection string from file

Salmaan

Member
Joined
Aug 20, 2003
Messages
21
Hi,

I am using VS.NET 2003 and C#. I am trying to create a SqlConnection by reading in the connection string from a text file. But this does not seem to work. I would really appreciate some help as to how I can accomplish this task. Here is my example code:

FileStream fs = new FileStream(@"C:\connPath.txt" , FileMode.Open, FileAccess.Read);

StreamReader m_streamReader = new StreamReader(fs);
path = m_streamReader.ReadLine();

SqlConnection sqlConn = new SqlConnection(path);

******* If I use the following it works just fine:

path = "data source = Saloo\\VSdotNET;database=Test_DB;trusted_connection=yes";

SqlConnection sqlConn = new SqlConnection(path);
*******

I have no clue at this moment as to how to fix this problem. I would really appreciate some help.

Thanks
 
Hello,
Thank you for you quick response. I have checked the string variables contentc in a message box and it includes everything in it. But Like I said I have no clue as to whats the problem.

Appreciate your help.
 
maybe when you are reading the path from the textfile with path = m_streamReader.ReadLine(); , its got a return at the end ( eg: \n ) , or maybe you are picking up the wrong line when making the connection string :-\ , i just tried with the same string and it returns fine , like this...
C#:
			StreamReader sr=new StreamReader(new FileStream(@"C:\my_file.txt",FileMode.Open));
			while(sr.Peek()!=-1)
			{
				string line=sr.ReadLine();
				if(line.StartsWith("data source"))
				{
					MessageBox.Show(line);
					// carry out your connection here.
				}
			}
			sr.Close();
 
Hi dynamic_sysop
Thanks for the response. I tried what you suggested...alas I still cant get it to work. I get the same stupid error. I am sure that I am screwing something up when I assign the string variable to the SqlConn. Please let me know if you find a solution.

Thanks a bunch for your suggestion.

Salmaan.
 
Hi guys,
I was able to solve the problem. In the file I had used 2 slashes for the data source name, thats what was causing the problem. When constructing a string in .Net you need two backslashes so .Net recognizes that it needs to interpret the second slash as an actual character not an escape sequence.

When the program is pulling in data from somewhere else (like a file or a win API call) it treats the entire string as a string literal without escape sequences.
Its working fine now. But I have a related question if you could please help me out. I am trying to read from a file that has a type of ".fil" I am unable to read this file through the stream reader. Can anyone please tell me how I have to cahnge my code in order to be able to read from a similar file type?

Any help would be greatly appreciated.

Salmaan.
 
Back
Top