Link to home
Start Free TrialLog in
Avatar of jakekula
jakekula

asked on

Write to XML configuration File

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...
Avatar of tovvenki
tovvenki

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
Avatar of Ryan Chong
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
Avatar of jakekula

ASKER

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...
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
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...
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Amazing code from ryancys! Thank you!