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.Confi gurationSe ttings.App Settings(" compNameCo nf") = "some string value"
message: "An unhandled exception of type 'System.NotSupportedExcept ion' 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.Confi gurationSe ttings.App Settings(" compNameCo nf")
Why can't I write to this file?
Thanks Guys...
I want to write to an XML configuration file but I get an error message saying the following:
code: System.Configuration.Confi
message: "An unhandled exception of type 'System.NotSupportedExcept
Additional information: Collection is read-only."
I am reading the file ok, with this code:
dim str as String
str = System.Configuration.Confi
Why can't I write to this file?
Thanks Guys...
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.Co nfig.Priva teFile)
' Retrieve a setting -
' Dim myString As String = a.GetSetting("SettingName" )
' Save a setting -
' a.SaveSetting("SettingName ", value)
' Delete a setting -
' a.DeleteSetting("SettingNa me")
'
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\applicat ion data" for the config file directory
sb.Append(Environment.GetF olderPath( Environmen t.SpecialF older.Appl icationDat a))
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.GetF olderPath( Environmen t.SpecialF older.Comm onApplicat ionData))
Case Config.SystemFile
'use "\Winnt\System32" for the config file directory
sb.Append(Environment.GetF olderPath( Environmen t.SpecialF older.Syst em))
End Select
'add the product name
sb.Append("\")
sb.Append(Application.Prod uctName)
'create the directory if it isn't there
If Not IO.Directory.Exists(sb.ToS tring) Then
IO.Directory.CreateDirecto ry(sb.ToSt ring)
End If
'finish building the file name
sb.Append("\")
sb.Append(Application.Prod uctName)
sb.Append(".config")
_configFileName = sb.ToString 'completed config filename
'if the file doesn't exist, create a blank xml
If Not IO.File.Exists(_configFile Name) Then
Dim fn As New IO.StreamWriter(IO.File.Op en(_config FileName, IO.FileMode.Create))
fn.WriteLine("<?xml version=""1.0"" encoding=""utf-8""?>")
fn.WriteLine("<configurati on>")
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("</configurat ion>")
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.SelectS ingleNode( _
"/configuration/appSetting s/add[@key =""" & key & """]")
'return the value or nothing if it doesn't exist
If Not Node Is Nothing Then
Return Node.Attributes.GetNamedIt em("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.S electSingl eNode( _
"/configuration/appSetting s/add[@key =""" & _
key & """]"), Xml.XmlElement)
If Not Node Is Nothing Then
'key found, set the value
Node.Attributes.GetNamedIt em("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.SelectS ingleNode( "/configur ation/appS ettings")
'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.SelectS ingleNode( "/configur ation")
Root.AppendChild(xd.Create Element("a ppSettings "))
Root = xd.DocumentElement.SelectS ingleNode( "/configur ation/appS ettings")
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.S electSingl eNode( _
"/configuration/appSetting s/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.SelectS ingleNode( "/configur ation/appS ettings")
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
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.Co
' Retrieve a setting -
' Dim myString As String = a.GetSetting("SettingName"
' Save a setting -
' a.SaveSetting("SettingName
' Delete a setting -
' a.DeleteSetting("SettingNa
'
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\applicat
sb.Append(Environment.GetF
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.GetF
Case Config.SystemFile
'use "\Winnt\System32" for the config file directory
sb.Append(Environment.GetF
End Select
'add the product name
sb.Append("\")
sb.Append(Application.Prod
'create the directory if it isn't there
If Not IO.Directory.Exists(sb.ToS
IO.Directory.CreateDirecto
End If
'finish building the file name
sb.Append("\")
sb.Append(Application.Prod
sb.Append(".config")
_configFileName = sb.ToString 'completed config filename
'if the file doesn't exist, create a blank xml
If Not IO.File.Exists(_configFile
Dim fn As New IO.StreamWriter(IO.File.Op
fn.WriteLine("<?xml version=""1.0"" encoding=""utf-8""?>")
fn.WriteLine("<configurati
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("</configurat
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.SelectS
"/configuration/appSetting
'return the value or nothing if it doesn't exist
If Not Node Is Nothing Then
Return Node.Attributes.GetNamedIt
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.S
"/configuration/appSetting
key & """]"), Xml.XmlElement)
If Not Node Is Nothing Then
'key found, set the value
Node.Attributes.GetNamedIt
Else
'key not found, create it
Node = xd.CreateElement("add")
Node.SetAttribute("key", key)
Node.SetAttribute("value",
'look for the appsettings node
Dim Root As Xml.XmlNode = xd.DocumentElement.SelectS
'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.SelectS
Root.AppendChild(xd.Create
Root = xd.DocumentElement.SelectS
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.S
"/configuration/appSetting
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.SelectS
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
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...
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\App lication 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(clsAppSetti ngs.Config .SystemFil e) 'Read config file from System Folder
To read value, use like:
Public value1 As String = appSettings.GetSetting("va lue1")
To save value, use like:
appSettings.SaveSetting("v alue1", "New Value1 ..")
To delete value, use like:
appSettings.DeleteSetting( "value1")
Hope this more clear and make helps, regards
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\App
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(clsAppSetti
To read value, use like:
Public value1 As String = appSettings.GetSetting("va
To save value, use like:
appSettings.SaveSetting("v
To delete value, use like:
appSettings.DeleteSetting(
Hope this more clear and make helps, regards
ASKER
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...
__________________________
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Amazing code from ryancys! Thank you!
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