我想在asp.net core 3.1中,每当有新客户在网站上注册时,更新连接字符串到xml文件中。
我的连接字符串格式是
<ConnectionStrings>
<add name="myConnectionString1" connectionString="server=localhost;database=myDb1;uid=myUser1;password=myPass;" />
<add name="myConnectionString2" connectionString="server=localhost;database=myDb2;uid=myUser2;password=myPass;" />
</ConnectionStrings>
我想用c#代码来实现,这样在注册时,这些数据会自动更新到xml文件中。
在我的头顶上。
你可以编辑你现有的XML如下
// Loads XML from file.
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\yourFile.xml");
// Get a list of all <ConnectionStrings> nodes.
XmlNodeList nodes = doc.SelectNodes("/ConnectionStrings");
// Loop through each found node.
foreach (XmlNode node in nodes)
{
// Search for the 'connectionString' attribute into the node.
XmlAttribute attrib = node.Attributes["connectionString"];
if (attrib != null)
{
// If the attribute could be found then you might want to get its value.
string currentValue = attrib.Value;
// Or do some stuff with the value. E.g: Set a new value based on the old one.
attrib.Value = currentValue + "your modification here";
}
}
// Finally you might want to save the document in other location.
doc.Save(@"C:\yourNewFile.xml";
编辑。 按照要求,你可以在连接字符串部分添加一个新的连接字符串元素,如下所示。(未经测试,可能需要一些调整)
using System.Configuration;
// Create a connection string element and add it to
// the connection strings section.
private bool CreateConnString(string name, string connString, string uId, string password)
{
try
{
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Get the current connection strings count.
int connStrCnt =
ConfigurationManager.ConnectionStrings.Count;
// Create a connection string element and
// save it to the configuration file.
// In your case 'connString' parameter should be
// something like "server=localhost;database=myDb1;"
ConnectionStringSettings csSettings =
new ConnectionStringSettings(name, connString +
"uid=" + uId + ";password=" + password + ";");
// Get the connection strings section.
ConnectionStringsSection csSection =
config.ConnectionStrings;
// Add the new element.
csSection.ConnectionStrings.Add(csSettings);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
return true;
}
catch (Exception e)
{
return false;
}
}