Solved

Write to XML configuration File

Posted on 2004-04-22
7
49,406 Views
Last Modified: 2012-04-13
Hi all,

I want to write to an XML configuration file but I get an error message saying the following:

code:            System.Configuration.ConfigurationSettings.AppSettings("compNameConf") = "some string value"

message:      "An unhandled exception of type 'System.NotSupportedException' occurred in system.dll
                     Additional information: Collection is read-only."

I am reading the file ok, with this code:

dim str as String

str =  System.Configuration.ConfigurationSettings.AppSettings("compNameConf")

Why can't I write to this file?

Thanks Guys...
0
Comment
Question by:jakekula
7 Comments
 
LVL 21

Expert Comment

by:tovvenki
ID: 10896740
Hi,
AppSettings is a readonly property. For using Configuration management in your application have a look at the Configuration management block available in Microsoft.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/cmab.asp

Regards,
Venki
0
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 10896839
Exactly the same issue i asked couple of weeks ago:

see: How to write value to config file?
http:Q_20954883.html

'a class for reading and writing XML style application settings
'sample usage:
'  Create the object -
'      Dim a As New AppSettings(AppSettings.Config.PrivateFile)
'  Retrieve a setting -
'      Dim myString As String = a.GetSetting("SettingName")
'  Save a setting -
'      a.SaveSetting("SettingName", value)
'  Delete a setting -
'      a.DeleteSetting("SettingName")
'
Public Class clsAppSettings
    Private _configFileName As String 'local var to hold the config file name
    Private _configFileType As Config 'local var to hold the config file type (private or shared)

    'config file options
    Public Enum Config
        SharedFile  'all users use the same config file
        PrivateFile 'each user has their own config file
        SystemFile 'all users use the same config file, config file put at System folder
    End Enum

    'constructor
    Public Sub New(ByVal ConfigFileType As Config)
        _configFileType = ConfigFileType 'remember this setting

        InitializeConfigFile() 'setup the filename and location
    End Sub

    'initialize the apps config file, create it if it doesn't exist
    Private Sub InitializeConfigFile()
        Dim sb As New System.Text.StringBuilder()
        'build the path\filename depending on the location of the config file
        Select Case _configFileType
            Case Config.PrivateFile 'each user has their own personal settings
                'use "\documents and settings\username\application data" for the config file directory
                sb.Append(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))
            Case Config.SharedFile 'all users share the same settings
                'use "\documents and settings\All Users\application data" for the config file directory
                sb.Append(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData))
            Case Config.SystemFile
                'use "\Winnt\System32" for the config file directory
                sb.Append(Environment.GetFolderPath(Environment.SpecialFolder.System))
        End Select

        'add the product name
        sb.Append("\")
        sb.Append(Application.ProductName)

        'create the directory if it isn't there
        If Not IO.Directory.Exists(sb.ToString) Then
            IO.Directory.CreateDirectory(sb.ToString)
        End If

        'finish building the file name
        sb.Append("\")
        sb.Append(Application.ProductName)
        sb.Append(".config")

        _configFileName = sb.ToString 'completed config filename

        'if the file doesn't exist, create a blank xml
        If Not IO.File.Exists(_configFileName) Then
            Dim fn As New IO.StreamWriter(IO.File.Open(_configFileName, IO.FileMode.Create))
            fn.WriteLine("<?xml version=""1.0"" encoding=""utf-8""?>")
            fn.WriteLine("<configuration>")
            fn.WriteLine("  <appSettings>")
            fn.WriteLine("    <!--   User application and configured property settings go here.-->")
            fn.WriteLine("    <!--   Example: <add key=""settingName"" value=""settingValue""/> -->")
            fn.WriteLine("  </appSettings>")
            fn.WriteLine("</configuration>")
            fn.Close() 'all done
        End If
    End Sub

    Public Function GetConfigFileLocation() As String
        Return _configFileName
    End Function

    'get an application setting by key value
    Public Function GetSetting(ByVal key As String) As String
        'xml document object
        Dim xd As New Xml.XmlDocument()

        'load the xml file
        xd.Load(_configFileName)

        'query for a value
        Dim Node As Xml.XmlNode = xd.DocumentElement.SelectSingleNode( _
                                  "/configuration/appSettings/add[@key=""" & key & """]")

        'return the value or nothing if it doesn't exist
        If Not Node Is Nothing Then
            Return Node.Attributes.GetNamedItem("value").Value
        Else
            Return Nothing
        End If
    End Function

    'save an application setting, takes a key and a value
    Public Sub SaveSetting(ByVal key As String, ByVal value As String)
        'xml document object
        Dim xd As New Xml.XmlDocument()

        'load the xml file
        xd.Load(_configFileName)

        'get the value
        Dim Node As Xml.XmlElement = CType(xd.DocumentElement.SelectSingleNode( _
                                           "/configuration/appSettings/add[@key=""" & _
                                           key & """]"), Xml.XmlElement)
        If Not Node Is Nothing Then
            'key found, set the value
            Node.Attributes.GetNamedItem("value").Value = value
        Else
            'key not found, create it
            Node = xd.CreateElement("add")
            Node.SetAttribute("key", key)
            Node.SetAttribute("value", value)

            'look for the appsettings node
            Dim Root As Xml.XmlNode = xd.DocumentElement.SelectSingleNode("/configuration/appSettings")

            'add the new child node (this key)
            If Not Root Is Nothing Then
                Root.AppendChild(Node)
            Else
                Try
                    'appsettings node didn't exist, add it before adding the new child
                    Root = xd.DocumentElement.SelectSingleNode("/configuration")
                    Root.AppendChild(xd.CreateElement("appSettings"))
                    Root = xd.DocumentElement.SelectSingleNode("/configuration/appSettings")
                    Root.AppendChild(Node)
                Catch ex As Exception
                    'failed adding node, throw an error
                    Throw New Exception("Could not set value", ex)
                End Try
            End If
        End If

        'finally, save the new version of the config file
        xd.Save(_configFileName)
    End Sub

    'delete an application setting, takes a key and a value
    Public Sub DeleteSetting(ByVal key As String)
        'xml document object
        Dim xd As New Xml.XmlDocument()

        'load the xml file
        xd.Load(_configFileName)

        'get the value
        Dim Node As Xml.XmlElement = CType(xd.DocumentElement.SelectSingleNode( _
                                           "/configuration/appSettings/add[@key=""" & _
                                           key & """]"), Xml.XmlElement)
        If Not Node Is Nothing Then
            'key found, delete the value

            'look for the appsettings node
            Dim Root As Xml.XmlNode = xd.DocumentElement.SelectSingleNode("/configuration/appSettings")
            If Not Root Is Nothing Then
                Root.RemoveChild(Node)
            End If
        Else
            'key not found, ignore            
        End If

        'finally, save the new version of the config file
        xd.Save(_configFileName)
    End Sub
End Class

Hope this helps
0
 

Author Comment

by:jakekula
ID: 10897011
Wow, there goes my big plan!

Ok so, could you please show me how I can use a normal XML file.  I assume I would add a XML file to my project in Visual Studio.Net and then call an object to hold the location of that file.  And then I would call read and write methods of that object to read and write to and from the XML file (that's a mouth-full)...

So how would I do all this in my Form code?

Thank You...
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 49

Expert Comment

by:Ryan Chong
ID: 10901150
Hi,

To use the above class file, first, try create a .config file (basically it's a XML file, just rename it as .config) like below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <!--   User application and configured property settings go here.-->
    <!--   Example: <add key="settingName" value="settingValue"/> -->
    <add key="value1" value="123" />
    <add key="value2" value="456" />
    <add key="value3" value="Hello World" />
    <add key="your own value" value="your value" />
  </appSettings>
</configuration>

this config file MUST named to your exe name accordingly, like if your application is called myApp. Try name the config file as myApp.config

According to this class file, you can put the myApp.config in 3 different places, according to your requirement (of course, you can amend it based on your requirement)

ApplicationData folder:
Like: C:\Documents and Settings\Administrator\Application Data\myApp\myApp.config

CommonApplicationData:
Like: C:\Documents and Settings\All Users.WINNT\Application Dat\myApp\myApp.config

System:
Like: C:\WINNT\System32

then call like below in your form:

Example:

Public appSettings As New clsAppSettings(clsAppSettings.Config.SystemFile) 'Read config file from System Folder

To read value, use like:

Public value1 As String = appSettings.GetSetting("value1")

To save value, use like:

appSettings.SaveSetting("value1", "New Value1 ..")

To delete value, use like:

appSettings.DeleteSetting("value1")

Hope this more clear and make helps, regards
0
 

Author Comment

by:jakekula
ID: 10914502
Ok, thanks for that.  But I don't wish to make a configuration file anymore.  I just want to change a value in an xml file.  I'll show you what I mean.

____________________________________________________________________________
This is the XML File:

<?xml version="1.0" encoding="utf-8" ?>
<Details>
      <mySettings>
            <add key="name" value="Bob" />
            <add key="address" value="10 Swan Street" />
      </mySettings>
</Details>
____________________________________________________________________________

1.  Now if I declare a variable to hold the value of "name"  which is "Bob", how do I read from the XML file and set the variable accordingly?

Dim str as String = ??? (get the name value from XML file)


2.  If I wish to change the name value from "Bob" to "Fred" and write it to the XML file, how would I do that?

At this point I'm not concerned with a configuration file anymore, just simple Read/Write XML.

Thank You all once again...
0
 
LVL 49

Accepted Solution

by:
Ryan Chong earned 85 total points
ID: 10916388
Try design your XML like:

c:\setting.xml:

<?xml version="1.0" encoding="utf-8"?>
<Details>
  <mySettings>
    <name value="Bob" />
    <address value="10 Swan Street" />
  </mySettings>
</Details>

then add these functions:

Private Function readXMLValue(ByVal filePath As String, ByVal key As String) As String
        Dim xd As New Xml.XmlDocument()

        'load the xml file
        xd.Load(filePath)

        'query for a value
        Dim Node As Xml.XmlNode = xd.DocumentElement.SelectSingleNode( _
                                  "/Details/mySettings/" & key)

        'return the value or nothing if it doesn't exist
        If Not Node Is Nothing Then
            Return Node.Attributes.GetNamedItem("value").Value
        Else
            Return ""
        End If
    End Function

    Private Function writeXMLValue(ByVal filePath As String, ByVal key As String, ByVal NewValue As String) As Boolean
        Try
            Dim xd As New Xml.XmlDocument()

            'load the xml file
            xd.Load(filePath)

            'save value
            Dim Node As Xml.XmlElement = CType(xd.DocumentElement.SelectSingleNode( _
                                           "/Details/mySettings/" & key), Xml.XmlElement)
            If Not Node Is Nothing Then
                'key found, set the value

                Node.Attributes.GetNamedItem("value").Value = NewValue

                xd.Save(filePath)
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function

finally, to read the value, try:

String myName = readXMLValue("c:\setting.xml", "name")
messagebox.show myName

to write the value, try:

writeXMLValue("c:\setting.xml", "name", "Fred")

cheers
0
 

Expert Comment

by:girlnerd
ID: 11130630
Amazing code from ryancys! Thank you!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

758 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

22 Experts available now in Live!

Get 1:1 Help Now