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

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");

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 read external app.config as xml file in winforms?

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.

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 accept User changes in app.config file after installing the setup file?

I have created one c# windows application setup.Then installed in user system.
I want to accept changes from app.config file that is my user change image folder location. First time my exe file accepting changes where I have modified in appsettings.
The problem is it does not accept user changes in app.config file. Why does this happen? What is wrong in my setup creation?
Please verify this code and give a suitable examples for this.
Here is my code
<appsettings>
<add key="SQLCN" value="Data Source=localhost;Initial Catalog=MyDB;Integrated Security=True" />
<add key="IMGFOLDER" value="D:\\ImageFolder" />
</appsettings>
private void SaveToIsolatedStorage(XDocument document, string file)
{
// Open the stream from IsolatedStorage.
IsolatedStorageFileStream stream = new IsolatedStorageFileStream(file, FileMode.Create, GetUserStore());
using (stream)
{
using (StreamWriter writer = new StreamWriter(stream))
{
document.Save(writer);
}
}
}
fldr = ConfigurationSettings.AppSettings["IMGFOLDER"];
Formload()
{
NewImageFolderCreation();
PopulateTreeview();
}
btnImagesave()
{
SaveImageAfterConvertion();
}
private void NewImageFolderCreation()
{
if (!System.IO.Directory.Exists(fldr))
{
System.IO.Directory.CreateDirectory(fldr);
MessageBox.Show("folder created");
}
else
{
MessageBox.Show("ImageFolder is available populate images into folder");
}
}
private void POpulateTreeview()
{
DirectoryInfo info = new DirectoryInfo(fldr);
TreeNode root = new TreeNode(info.Name);
root.Text = "";
//eng = OcrEngineManager.CreateEngine(OcrEngineType.Professional, false);
//eng.Startup(null, null, null, null);
TreeNode node = new TreeNode();
TrvImageFile.Nodes.Add(root);
FileInfo[] subfileinfo = info.GetFiles("*.*");
if (subfileinfo.Length > 0)
{
for ( j = 0; j < subfileinfo.Length; j++)
{
root.Nodes.Add(subfileinfo[j].Name);
}
}
TrvImageFile.ExpandAll();
}
SaveImageAfterConvertion()
{
if (!System.IO.Directory.Exists(fldr))
{
System.IO.Directory.CreateDirectory(fldr);
doc.Save(ConfigurationSettings.AppSettings ["SaveImagefolderPath"] + "\\" + Newtxtfilename + ".txt",
Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
MessageBox.Show("folder created and image output saved");
}
else
{
doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" +Newtxtfilename + ".txt",
Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
MessageBox.Show("ImageFolder is available images are Saved into folder Now");
}
}
The whole point of a configuration file is that you can make changes without recompiling.
When in comes to winforms, you need to ensure the correct config file is changed (it is rarely named app.config - it is normally <name of app>.exe.config.
The app.config file you see in visual studio is a template - when compiling the application it will be copied to the output folder and renamed to <name of app>.exe.config. This is the file that should be changed.
The user will normally need to exit from the application and restart in order for the changed configuration settings to take hold.

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