0

テキストボックスから4行を読み取る必要があるクラスにこのコードがありますが、プログラムが停止するため、エラーの場所がわかりません。悪い方向には進んでいないと思いますが、少し改善する必要があります。

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;
       }
    }
}

これは私がフォームでそれを呼び出す方法です

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

1 に答える 1

1

を取り外します

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

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

または、以下のようにすることもできます

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]);
}

接続の詳細をテキスト ファイルに保存する理由がわかりません。.Net では、Web アプリケーションまたはアプリ構成ファイルの場合、接続文字列を web.config に格納できます。

詳細については、以下のリンクを参照してください。

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

于 2013-07-27T07:14:47.720 に答える