how to read external app.config as xml file in winforms? - c#

How to read app.config file as normal xml and read the connectionString Key/value
from configuration ->connectionStrings node
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="appConnStr" connectionString="Data Source=DEV6-PC;Initial Catalog=ireg.est;Persist Security Info=True;User ID=sa;Password=sa#123" providerName=".NET Framework Data Provider for SQL Server"/>
</connectionStrings>
<configuration>

var element = XDocument.Load("filepath")
.Descendants("connectionStrings")
.FirstOrDefault();
var connStrings = new Dictionary<string,string>();
if(element != null)
{
foreach(var item in element.Elements("add"))
{
var name = (string)item.Attribute("name");
var connString = (string)item.Attribute("connectionString");
connStrings.Add(name,connString);
}
}

try this: here im reading the file as an xml document and retrieving the connection string attribute.
string connString=null;
XmlDocument xmldoc = new XmlDocument();
xmldoc.load("yourconfigfielpath"); // add your file path here.
XmlNodeList nodeList = xmlDoc.SelectNodes("/xml/configuration/connectionstrings");
foreach (XmlNode node in nodeList)
{
connString=node["add"].GetAttribute("connectionString");
}
hope this helps.

Related

C# check if handler is present in Web.Config

In my Web.Config file I have the following:
<system.webServer>
<handlers>
<add name="HANDLERNAME" verb="*" path="PATH.axd" type="HANDLERTYPE">
</handlers>
</system.webServer>
Before I run a particular bit of code, I want to check to see if the handler is present in my Web.Config file.
Is this something I'm able to do?
I've tried: ConfigurationManager.GetSection("system.webServer/handlers") with no success, as this returns null.
Any help would be greatly appreciated!
I found two way to check for the handlers in the web.config
XmlDocument doc = new XmlDocument();
doc.Load(path); *//path is the location of the web.config file*
XmlElement root = doc.DocumentElement;
XmlNode nodes = root.SelectSingleNode("/system.webServer");
XmlNodeList childnotes = nodes.ChildNodes;
bool isExist = false;;
foreach (XmlNode node in childnotes)
{
if (node.Name.Contains("handlers"))
{
isExist = node.OuterXml.Contains("HANDLERNAME");
}
}
you can check the value of isExist
The other way is to get entire web.config as a string and check if it contains HANDLERNAME

How to save a New Xml file using app.config?

I have to save a file with the help of app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appsetting>
<add key ="filename" value ="abc.xml"></add>
<add key="filepath" value ="C:\\Users\\saket.parasar.jha"></add>
</appsetting>
</configuration>
My code for saving the xml file to the prescribed path-:
XmlDocument doc = new XmlDocument();
//XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
//doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
{
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "1";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
AddUpdateAppSettings("filename", "abc.xml");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
I have to write that xml file to C:\Users\saket.parasar.jha" using c#...pls help me out, I am new to this topic.I tried a lot but was nt able to save that file.
First of all, you can never modify app.config file programmatically. The settings inside are never to be changed while your app is running. These settings are like "pre-launch". If you need any settings modificable by a user, use Settings File (Add > New Item > General > Settings File), the one with the extension *.settings. Also, I don't see you trying to get your settings from your configuration file, you're only saving them there (but you can't do that, the reason is above).
After you get your path properly, you can save your file there.
P.S.: App.config is not allowed to be modified, because it sits in the same directory as the app (with modified name like MyApplication.exe.config); when you app is installed on a destination system, the destination directory will most likely be "Program Files". As you understand, any attempt to modify the config will require elevated privileges (like an administrator's). That means your app is VERY user unfriendly.
Why don't you save your XmlDocument? something like
doc.Save("C:\\Users\\saket.parasar.jha\\abc.xml");

Read a connection string from a XML file

I've read about all I could get on how to read from an XML file, but I can't get anything done. I want to read a connectionstring from an XML file, plain and simple, nothing more.
My XML looks like
<?xml version="1.0" standalone="yes"?>
<connectionString>
<conn>"adsf"</conn>
</connectionString>
And I've tried varios way with
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(xmlLoc);
while (reader.MoveToNextAttribute())
{
XmlNode a = doc.ReadNode(reader);
textBox1.Text = Text + a.Name;
}
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlLoc); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/connectionString");
foreach (XmlNode xn in xnList)
{
XmlNode example = xn.SelectSingleNode("conn");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
I'm missing something and I'm not sure what, this should be a very simple task, but I can't get it done. Any help?
I'm trying to do it in a WIndows form application program.
I'm missing something?
Yes. .NET has a built in mechanism for storing your connection string, inside an App.config file, there is no reason to manually store it and parse it yourself.
Right click your project, go to Add -> New Item
Then, add a "Application Configuration File":
Once it opens, add a connectionStrings node to it, as follows:
// This is an example of a connectionString node. You may add child
// values to it as follows
<connectionStrings>
<add name="YourConnectionStringKey"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YourDB;Trusted_Connection=Yes" />
</connectionStrings>
Then, you access it using ConfigurationManager.ConnectionStrings:
string connectionString =
ConfigurationManager.ConnectionStrings["YourConnectionStringKey"].ConnectionString;
You can use linq to xml.
var xmlStr = File.ReadAllText("fileName.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("word").
Where(x => x.Element("connectionString").Value.Equals("conn"));
Console.WriteLine(result);
This might work (or may be some changes you need to make.
var x = XElement.Parse(#"<?xml version=""1.0"" standalone=""yes""?><connectionString><conn>adsf</conn></connectionString>");
// or var x = XElement.Load(#"c:\temp\my.xml");
var s = x.Element("conn").Value;
If you still have not found your answer then try this (a bit old school but it worked for me)
public class Common
{
public Common()
{
}
// public static string GetXML()
// {
// return #"C:\MyLocation\Connections.xml";
// }
public static string GetXMLconn(string strConn)
{
string xmlConStr = "";
//
string XMLconn = #"C:\Mylocation\Connections.xml";
// Get the Connection String from the XML file.
XmlTextReader textReader = new XmlTextReader(XMLconn);
textReader.Read();
while (textReader.Read())
{
// Read the currect element in the loop
textReader.MoveToElement();
// If the element name is correct then read and assign the connection string
if (textReader.Name == strConn)
{
xmlConStr = textReader.ReadString();
}
}
textReader.Close();
return xmlConStr;
}
}

XML document processing cant load file

I am writing an application where i need to pull information out of a XML Document.
My XML document is stored in my projects bin/ Debug file.
I cant get it working.
XML document named informationData:
<xml>
<information>
<name >stian</name>
<surname>Kruger</surname>
<tel>0825514302</tel>
<photo>1234JLJ.jpg</photo>
</information>
</xml>
my call code:
private void btnReadXML_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("informationData.xml");
XmlNodeList dataNodes = xmlDoc.SelectNodes("/information");
foreach (XmlNode node in dataNodes)
{
Name = node.SelectSingleNode("name").InnerText;
Surname = node.SelectSingleNode("surname").InnerText;
TelNumber = Convert.ToInt32(node.SelectSingleNode("tel").InnerText);
}
}
Your XPath selector is wrong. Replace:
XmlNodeList dataNodes = xmlDoc.SelectNodes("/information");
with:
XmlNodeList dataNodes = xmlDoc.SelectNodes("//information");
or with:
XmlNodeList dataNodes = xmlDoc.DocumentElement.SelectNodes("information");
Also make sure that the XML file is present in the same folder as the running executable (you said bin/Debug/informationData.xml). If the XML file is part of your Visual Studio project you could select it and in the properties set Copy to Output Directory to Copy if newer. This way VS will automatically copy the XML file to this output folder everytime you compile the project.
You can use this code
<?xml version="1.0" encoding="utf-8" ?>
<information>
<name >stian</name>
<surname>Kruger</surname>
<tel>0825514302</tel>
<photo>1234JLJ.jpg</photo>
</information>
var xmlDoc = XDocument.Load("informationData.xml");
var name = xmlDoc.Element("name").Value;
var surname = xmlDoc.Element("surname").Value;
var telNumber = Convert.ToInt32(xmlDoc.Element("tel").Value);
add <?xml version="1.0" encoding="utf-8"?> as first line in XML file

How to check if the System.webServer/Security/requestFiltering section exists programmatically?

I want to be able to determine programmatically if the System.webServer/Security/requestFiltering section exists inside the the web.config file of my application.
I am able to do it for other sections like system.web using the code below, but so far no luck with system.WebServer.
var config = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
Label1.Text = section.MaxRequestLength.ToString();
Why don't you read the web.config just like any XML file and find the nodes that way? You could do something like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/Web.config"));
XmlNode n = xmlDoc.SelectSingleNode("/configuration/System.webServer/Security/requestFiltering");
if (n != null)
{
// Do whatever you want...
}

Categories

Resources