Solved

C# - Read / Write Data to App.Config file in a specific directory

Posted on 2016-08-03
9
137 Views
Last Modified: 2016-08-05
I have an app.config file which I'm storing in a different directory structure.  Is it possible to Read / Write to that config file?

Read
 key = ConfigurationManager.AppSettings[ReportName];

Open in new window

Write
config.AppSettings.Settings.Add("key1", "value");

Open in new window

MyDir
--App.Config
MyApp
--MyApp.exe
--App.config

I want to access App.Config in "MyDir" Directory
0
Comment
Question by:CipherIS
  • 6
  • 3
9 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41741680
Hi ;

You should be able to get an instance of the configuration object and use that to access the section of the config file. Please see this Microsoft doc which has an example. ConfigurationManager.OpenMappedExeConfiguration Method (ExeConfigurationFileMap, ConfigurationUserLevel, Boolean)
0
 
LVL 1

Author Comment

by:CipherIS
ID: 41742507
That is what I thought.  I tried that.

 Configuration config = ConfigurationManager.OpenExeConfiguration(sConfig);

key = config.AppSettings[ReportName];

Open in new window

However for "config.AppSettings" I receive an error

ConfigurationElement.this[Configuration.Property] is inaccessible due to its protection level.

For sConfig I'm passing in like "C:\MyDir\App.config".
0
 
LVL 1

Author Comment

by:CipherIS
ID: 41742653
Below is my Code.  Still receiving an error.
string key = string.Empty;
string sConfig = string.Empty;

Files files = new Files();
sConfig = Path.Combine( files.ReturnSaveLocation(), @"App.Config");

Configuration config = ConfigurationManager.OpenExeConfiguration(sConfig);
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = sConfig;
Configuration mConfig = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None, true);

string s = aem.ReportName;
key = mConfig.AppSettings[s];  //Receiving error here.  Inaccessible due to protection level.

Open in new window

0
 
LVL 1

Author Comment

by:CipherIS
ID: 41743088
Having issues with the app.config.  Looking at just reading/writing to XML.

Is there a way to read write to XML so I can have similar result?

<key=1>  <value=123>
<key=2>  <value=abc>

I want to be able to check to see if key 1 exists and if it doesn't add it to the XML file along with it't value and so on.

Thanks.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 1

Author Comment

by:CipherIS
ID: 41743170
Hope this makes sense.  Check the xml for Key value 3.
<?xml version="1.0" encoding="utf-8"?>
<Reports>
    <report>
        <key>1</>
        <value>123</value>
    </report>
    <report>
        <key>2</>
        <value>abc</value>
    <report>
</Reports>

Open in new window

if it doesn't exist then add it.
<?xml version="1.0" encoding="utf-8"?>
<Reports>
    <report>
        <key>1</>
        <value>123</value>
    </report>
    <report>
        <key>2</>
        <value>abc</value>
    </report>
    <report>
        <key>3</>
        <value>12ab</value>
    </report>
</Reports>

Open in new window

If it does exist then update it
<?xml version="1.0" encoding="utf-8"?>
<Reports>
    <report>
        <key>1</>
        <value>123</value>
    </report>
    <report>
        <key>2</>
        <value>abc</value>
    </report>
    <report>
        <key>3</>
        <value>ab12</value>
    </report>
</Reports>

Open in new window

0
 
LVL 1

Author Comment

by:CipherIS
ID: 41743224
This is what I was able to come up with so far.
    public class XML
    {
        public string ReadXML(string key)
        {
			bool found = false

			return found;
        }

        public bool WriteXML(string sKey, string sValue)
        {
            Files file = new Files();
            string saveLocation = file.ReturnSaveLocation();
            string xml = string.Empty;

            xml = Path.Combine(saveLocation, "Reports.xml");

            XmlDocument doc = new XmlDataDocument();
            doc.Load(xml);

            XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
            namespaces.AddNamespace("Reports", "http://www.w3.org/2001/XMLSchema");

            XmlNode nextNode = doc.SelectSingleNode("/Reports", namespaces);

            XmlElement report = doc.CreateElement("Export");

            XmlElement key = doc.CreateElement("Key");
            key.InnerText = sKey;

            XmlElement value = doc.CreateElement("Value");
            value.InnerText = sValue;

            nextNode.AppendChild(key);
            key.AppendChild(value);

            doc.Save(xml);

            return true;
        }
    }

Open in new window


It is inserting key and value but not correctly.  It is inserting it as

<key>1<value>123</value</key>

Can't get <report> added.  Don't know if I need to or not.  

Any suggestions?
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 41743254
Hi CipherIS;

Here is a code snippet that will work with an XML Document. I modified the schema a little to be less verbose and simpler to modify.
using System.Xml.Linq;

// Location and name of the XML file
string filePathName = "C:\\Working Directory\\reports.xml";
// Load the XML into memory
XDocument xdoc = XDocument.Load(filePathName);
string keyToCheck = "5";
string valueToApply = "Fernando";
// Query the document
XElement result = xdoc.Root.Descendants("key")
                      .Where(k => k.Value == keyToCheck)
                      .Select(k => k)
                      .FirstOrDefault();
// Check to see if the key was found
if(result == null) {
    // Key was NOT found so add it to the document
    XElement newElement = new XElement("key", keyToCheck, new XAttribute("value", valueToApply));
    // Add it to the document
    xdoc.Root.Element( "report" ).Add( newElement );
} else {
    // Modify the value of the one it found
    result.Attribute("value").SetValue(valueToApply);
}
// Save the document back to the file system
xdoc.Save( filePathName );

Open in new window

This is what the new schema looks like
<?xml version="1.0" encoding="utf-8"?>
<Reports>
  <report>
    <key value="123">1</key>
    <key value="abc">2</key>
    <key value="12zz">3</key>
    <key value="abc123">5</key>
  </report>
</Reports>

Open in new window

0
 
LVL 1

Author Closing Comment

by:CipherIS
ID: 41743318
Thanks so much.  The code is cleaner and easier to understand also.
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41743365
Not a problem CipherIS, glad I was able to help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now