2015-10-07 63 views
1

我試圖將用戶ID存儲在我的配置文件中,然後我想通過我的程序訪問許多原因。我在配置文件中有這樣的appSettings部分;將值存儲在appSettings

<appSettings> 
    <add key="userID" value="1" /> 
</appSettings> 

然後我在一個方法中設置值;

private void hrButton_Click(object sender, RoutedEventArgs e) 
{ 
    DataAccessor da = new DataAccessor(); 
    DataRowView dataRow = (DataRowView)dataGrid.SelectedItem; 

    // Open App.Config of executable 
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

    // Add an Application Setting. 
    config.AppSettings.Settings.Add("userID", dataRow.Row.ItemArray[0].ToString()); 

    // Save the changes in App.config file. 
    config.Save(ConfigurationSaveMode.Modified); 

    da.SetUserDetails(); 
    NavigationService.Navigate(new Uri(@"View/HRSystem/HRSystem.xaml", UriKind.Relative)); 
} 

在試圖訪問並在另一箇中使用它之前;

public List<string> SetUserDetails() 
{ 
    string userID = ConfigurationManager.AppSettings.Get("userID"); 
    MessageBox.Show("userID: "+userID); 

    string constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString; 
    using (OleDbConnection dbfCon = new OleDbConnection(constr)) 
    { 
     try 
     { 
      dbfCon.Open(); 
      OleDbDataReader myReader; 
      OleDbCommand sqlCmd = new OleDbCommand("SELECT em_pplid FROM employs WHERE em_pplid = "+ userID + "", dbfCon); 
      myReader = sqlCmd.ExecuteReader(); 

      List<string> listUser = new List<string>(); 
      while (myReader.Read()) 
      { 
       listUser.Add(myReader[0].ToString()); 
       return listUser; 
      } 
     } 
     catch (MySqlException) 
     { 
      throw; 
     } 
    } 
    return null; 
} 

然而,當我在消息框中它仍然設置爲1。我以前沒有使用過的appSettings部分顯示userID,是有一個原因它始終是1?我正在運行Visual Studio 2015,C#WPF。

回答

2

上線添加config.AppSettings.Settings.Remove("userID");略高於config.AppSettings.Settings.Add();

但正確的方式來保存這些信息是使用Settings File

集:

Properties.Settings.Default.userID = dataRow.Row.ItemArray[0].ToString(); 
Properties.Settings.Default.Save(); 

Retreive:

var userId = Properties.Settings.Default.userID; 
+0

感謝您的回覆,雖然即使在做這個用戶ID仍然被設置爲1 – CBreeze

+0

更新:使用設置文件方法代替工作,感謝您的幫助。 – CBreeze

0

嘗試

config.AppSettings.Settings.Remove('userID'); 

config.AppSettings.Settings.Add('userID', dataRow.Row.ItemArray[0].ToString()); 

但你不應該存儲在配置文件中的用戶ID。你應該將其保存在會話或Cookie的