gpt4 book ai didi

c# - 在 appSettings 中存储值

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:15 27 4
gpt4 key购买 nike

我试图在我的配置文件中存储一个用户 ID,然后出于多种原因我想在整个程序中访问它。我在配置文件中有 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.Remove("userID");config.AppSettings.Settings.Add(); 正上方的线上

但是保存此类信息的正确方法是使用 Settings File

设置:

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

检索:

var userId = Properties.Settings.Default.userID;

关于c# - 在 appSettings 中存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com