For the following:
<configProtectedData >
<providers>
<clear />
<add CertSubjectDistinguishedName="localhost" name="X509ProtectedConfigProvider" type="X509ProtectedConfig.X509ProtectedConfigProvider, X509ProtectedConfigProvider" />
</providers>
</configProtectedData>
how can i modify:
CertSubjectDistinguishedName="localhost"
and substitute "localhost" with something different?
I can't figure out how to read in "configProtectedData " section and modify it.
thanks
I solved it using XMLDocument:
string path = Path.Combine(targetDirectory, applicationExecutableName);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNode node = xmlDoc.SelectSingleNode("configuration/configProtectedData/providers");
node.InnerXml = string.Format("<add CertSubjectDistinguishedName=\"{0}\" CertStoreName=\"{1}\" name=\"X509ProtectedConfigProvider\" type=\"ProtectedConfigProvider.X509ProtectedConfigProvider, X509ProtectedConfigProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=098027505e2ed139\" />", certSubject, certStoreName);
xmlDoc.Save(path);
If anyone knows a better way please post a sample. thanks
Related
I am trying to Deserialize XML configuration file stored in %LOCALAPPDATA%\Configuration\Configuration.XML. I want to read the key value section and store it in the local variable.
The XML file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FolderPath" value="C:\\Data" />
<add key="Name" value="xxx" />
<add key="Type" value="xxx" />
</appSettings>
</configuration>
ConfigurationManager.Appsettings.Get("FolderPath") does not work because the xml file is in the different location.
So I tried with the following code, which does not work.
var configFile = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Configuration", "Configuration.XML")
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var appSettings = configuration.GetSection("appSettings").SectionInformation;
Please help me to read the configuration.XML as shown above.
Thank you.
Thanks for your suggestions #jdweng.
I was able to solve the issue
var configFile = Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "Configuration", "Configuration.XML"));
if (File.Exists(configFile))
{
ConfigurationDetails = new Dictionary<string, string>();
XDocument doc = XDocument.Load(configFile);
var elements = doc.Descendants("add");
foreach (var element in elements)
{
ConfigurationDetails.Add(element.Attribute("key").Value, element.Attribute("value").Value);
}
}
New to C# programming, and I'm kind of stuck right now. How would I create a simple program that let's me extract and display the data source value in connectionStrings. And lets me modify the Id and password? Am I on the right track with parsing
Document X = XDocument.Load("C:\Users\Odd_Creature\Desktop\SecureConfig\\UserProfiles\UserInfo.exe.config")
var configuration= X.Element("configuration").Element("connectionStrings");
var location = configuration.Descendants("").Attributes("").FirstOrDefault().Value;
doc.Save(xmlfile);
XMLFILE
<configuration>
<configProtectedData />
<system.diagnostics />
<system.windows.forms />
<uri />
<appSettings>
<add key="GenerateProfile" value="true" />
<add key="TestScore" value="30" />
<add key="TestApplicationName" value="User Account" />
</appSettings>
<connectionStrings>
<add name="MyExample.database" connectionString="data source=.\SQLEXPRESS;initial catalog=wadb;integrated security=false;encrypt=true;trustservercertificate=true;User Id=Tester;Password=Test1;"
providerName="System.Data.SqlClient" />
</connectionStrings>
This would be a brute force approach to parsing the connection string from an XML file.
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("settings.xml");
string connectionStrings = xmlDoc.GetElementsByTagName("connectionStrings")[0].InnerXml;
string tag = "connectionString=\"";
string connectionString = connectionStrings.Substring(connectionStrings.IndexOf(tag) + tag.Length);
string[] tokens = connectionString.Split(';');
Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("data source=")));
Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("User Id=")));
Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("Password=")));
}
And the output would be:
data source=.\SQLEXPRESS
User Id=Tester
Password=Test1
With a little more code, you should be able to edit these fields, and then use xmlDoc.Save() to update your changes.
I'm relatively new to C#, and just started using XmlElement and the SingleNode Method. For some reason "customSettings" keeps returning null, although the XML Document is being loaded correctly. I've checked that by loading it as a string. I've tried everything i could imagine so far including the attempt in the comment. Any help or suggestions are much appreciated. Here is my XML Doc:
EDIT: works with solution from CodingYoshi, but is there a better way?
EDIT: changed XML and code for NSGaga to resolve read only exception with NameValueCollection in user.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="users_fächer" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<users_faecher>
<add key="user1" value="value1" />
<add key="user2" value="value2" />
</users_faecher>
</configuration>
Code:
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Users.config");
string new_fächer = input[1];
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = dir;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
ConfigurationSection myParamsSection = config.GetSection("users_faecher");
string myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
XmlDocument sectionXmlDoc = new XmlDocument();
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
NameValueSectionHandler handler = new NameValueSectionHandler();
NameValueCollection users_fächer = handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
users_fächer.Set(user, new_fächer);
config.Save(ConfigurationSaveMode.Modified, true);
This will get you the first add element:
doc.ChildNodes[0].NextSibling.ChildNodes[1].ChildNodes[0].ChildNodes[0];
This will get you the first add element's value attribute.
doc.ChildNodes[0].NextSibling.ChildNodes[1]
.ChildNodes[0].ChildNodes[0].Attributes["value"].Value;
I have an xml File
<configuration>
<MetisLinks>
<add key="MetisInternal" value="https://xyz.abc.com/" />
<add key="Hermes" value="https://hermes.abc.com/" />
<add key="umar" value="https://umar.abc.com/" />
</MetisLinks>
</configuration>
I need to add custom key and value in this MetisLink node using C#. Also if it already exists than overwrite.I searched for different solution but the exact was not on internet.
Thanks in advance!
This code should work for you:
string keyToAdd = "testKey";
string valueToAdd = "http://test.com";
XmlDocument doc = new XmlDocument();
doc.Load(#"D:\build.xml");
XmlNode root = doc.DocumentElement;
XmlElement existingMatchingElement = (XmlElement)root.SelectSingleNode(string.Format("//MetisLinks/add[#key='{0}']", keyToAdd));
if (existingMatchingElement != null)
{
existingMatchingElement.SetAttribute("value", valueToAdd);
}
else
{
XmlNode myNode = root.SelectSingleNode("MetisLinks");
var nodeToAdd = doc.CreateElement("add");
nodeToAdd.SetAttribute("key", keyToAdd);
nodeToAdd.SetAttribute("value", valueToAdd);
myNode.AppendChild(nodeToAdd);
}
doc.Save(#"D:\build.xml");
I created a file at D:\build.xml and copied your xml there, you could place your file containing that xml anywhere and just use that path in the code
I've got this xml file:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup><supportedRuntime version="v2.0.50727"/></startup>
<applicationSettings>
<MyApp.Settings>
...
...
</XNet.XManager.Properties.Settings>
</applicationSettings>
I need to replace the <startup> node with:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
Which is the best way?
If you use LINQ to XML (it's an XML API rather than LINQ):
XDocument doc = XDocument.Load("dat.xml");
XElement startup1 = doc.Root.Element("startup");
startup1.Remove();
doc.Root.Add(new XElement("startup", new XAttribute("useLegacyV2RuntimeActivationPolicy", "true"),
new XElement("supportedRuntime", new XAttribute("version", "v4.0"),
new XAttribute("sku", ".NETFramework"),
new XAttribute("Version", "v4.5.2"))));
doc.Save("dat.xml");
Edit - as Jon Skeet suggested the proper way should be to use XElement.ReplaceWith :
XDocument doc = XDocument.Load("dat.xml");
XElement startup1 = doc.Root.Element("startup");
startup1.ReplaceWith(new XElement("startup", new XAttribute("useLegacyV2RuntimeActivationPolicy", "true"),
new XElement("supportedRuntime", new XAttribute("version", "v4.0"),
new XAttribute("sku", ".NETFramework"),
new XAttribute("Version", "v4.5.2"))));
doc.Save("dat.xml");
You can use the below code to do the same, where the element is being find and it is replaced with other.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path to your file");
string strXml =
#"<startup useLegacyV2RuntimeActivationPolicy='true'>
<supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.5.2' />
</startup>";
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml = strXml;
xmlDoc.SelectSingleNode("startup").AppendChild(xmlDocFragment);
Update: Using LINQ. Working Tested Code
var doc = XDocument.Load(#"path to file");
string input = #"<startup useLegacyV2RuntimeActivationPolicy='true'>
<supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.5.2' />
</startup>";
var replacement = XElement.Parse(input);
var nodeToReplace = doc.Descendants().Elements("startup").FirstOrDefault();
nodeToReplace.ReplaceWith(replacement);
doc.Save(#"path to file");
Console.WriteLine(doc);
Console.Read();