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 回答