Marek
Marek

Reputation: 3575

StreamReader in class for SqlConnection

I have this code in class which should read 4 lines from textbox but the program stops so I don't know where the error is. I think Im not on a bad way but I need to little improve it.

using System.Data.SqlClient;
using System.IO;

namespace tours
{
   class myConnection
   {
       public static SqlConnection GetConnection()
       {
            string path = "C:\\Users\\marek\\Documents\\Visual Studio 2012\\Projects\\tours\\tours\\sql_string.txt";

            StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));

            while (sr.Peek() >= 0)
            {
            }

            string str = "Data Source='" + sr.ReadLine() + "';Initial Catalog ='" + sr.ReadLine() + "' ;user='" + sr.ReadLine() + "';password= '" + sr.ReadLine() + "'";

            SqlConnection con = new SqlConnection(str);
            con.Open();
            return con;
       }
    }
}

This is how I call it in form

private void nastaveni_Load(object sender, EventArgs e)
{
        try
        {
            nacti_spojeni();
            myConnection.GetConnection();
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex);
        }
}

Upvotes: 0

Views: 667

Answers (1)

Damith
Damith

Reputation: 63065

Remove the

//while (sr.Peek() >= 0)
//{

//}
string str = "Data Source='" + sr.ReadLine() + "';Initial Catalog ='" + sr.ReadLine() + "' ;user='" + sr.ReadLine() + "';password= '" + sr.ReadLine() + "'";

Or you can do as below

var lines =  File.ReadAllLines(path);
if (lines.Length >=4)
{
    string str = string.Format("Data Source='{0}';Initial Catalog ='{1}' ;user='{2}';password= '{3}'"
        , lines[0], lines[1], lines[2], lines[3]);
}

I'm not sure why you save connection details on text file. in .Net we can store connection string in web.config if it is web application or otherwise app config file

Read more about this please check below links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.100).aspx

Upvotes: 1

Related Questions