2015-08-28 50 views
0

我已經完成構建應用程序。LINQ SQL連接字符串在從TXT文件讀取時不起作用

我列表中的最後一件事是將SQL連接字符串放在文件中,而不是硬編碼(以便用戶可以編輯它,如果需要的話)。

連接失敗,我從DataContext中得到一個異常。

連接字符串definitley正確。唯一改變了的,因爲它全部正常工作,我已經把連接字符串放在一個txt文件中而不是硬編碼了。

之前(我的應用程序連接到數據庫罰款):

private string conString = "Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True"; 
    public LogIn() 
    { 

     dc = new MyDataContext(conString); 
     if (dc.DatabaseExists()) 
     { 
      InitializeComponent(); 
     } 
     else 
     { 
      MessageBox.Show("There has been an error, please try again. If ther problem persists, call you know who. Error: Can't connect to database! Make sure the network is all good (connection to ADMIN PC)" /*+ e.ToString()*/); 
     } 
    } 

NOW(不工作):

private string conString; 
    public LogIn() 
    { 

    try 
     { 
      ConnectionString.globalConString = System.IO.File.ReadAllText("connString.txt").ToString(); 
      this.conString = ConnectionString.globalConString; 
     } 
     catch (IOException e) 
     { 
      MessageBox.Show("There was an error reading the conn string file."); 
      return; 
     }   

     dc = new MyDataContext(conString); 
     if (dc.DatabaseExists()) 
     { 
      InitializeComponent(); 
     } 
     else 
     { 
      MessageBox.Show("There has been an error, please try again. If ther problem persists, call you know who. Error: Can't connect to database! Make sure the network is all good (connection to ADMIN PC)" /*+ e.ToString()*/); 
     } 
    } 

TXT文件只包含:

Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True 

的文件在正確的位置和應用程序可以讀取它(我已經輸出與MessageBox.Show())的字符串。

我能想到的是,該字符串實際上不是一個字符串,實際上是一些奇怪的格式?我不知道。

順便說一句,嘗試連接的位拋出異常(不是由文件讀取位 - 代碼讀取文件,但DataContext不喜歡傳遞給它的字符串)。

任何想法??

謝謝

回答

0

嘗試刪除雙\\HP

Data Source=HP\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True 

定義一個C#字符串時,雙反斜線將是有效的,因爲你需要躲避反斜槓字符,但是從文件讀取時,它將被視爲兩個反斜槓字符。

0

您不需要在文本文件中僅在代碼中轉義反斜槓。該文件應包含:

Data Source=HP\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True 
0

你並不需要把雙反斜線嘗試

Data Source=HP\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True 
相關問題