在appSettings中存储值
本文关键字:存储 appSettings | 更新日期: 2023-09-27 18:16:29
我试图在我的配置文件中存储一个userID,然后由于各种原因我想在整个程序中访问它。我在配置文件中有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;
}
然而,当我在消息框中显示userID
时,它仍然被设置为1。我以前没有使用过appSettings
部分,有什么原因它总是1吗?我运行的是Visual Studio 2015, c# WPF。
在config.AppSettings.Settings.Add();
上方添加config.AppSettings.Settings.Remove("userID");
但是保存这些信息的正确方法是使用设置文件
:
Properties.Settings.Default.userID = dataRow.Row.ItemArray[0].ToString();
Properties.Settings.Default.Save();
检索:
var userId = Properties.Settings.Default.userID;
try
config.AppSettings.Settings.Remove('userID');
config.AppSettings.Settings.Add('userID', dataRow.Row.ItemArray[0].ToString());
但是您不应该在配置文件中存储用户id。您应该将其保存在会话或Cookie