RSS

カテゴリー : VB.NET

[.NET] 構成ファイルの簡単な読み込み書き込み方法について

VB.NET用のサンプルソース
C#用に書き換えてください。

— App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>

— 読み取りアクセス
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MessageBox.Show("Application Name = " & _
System.Configuration.ConfigurationSettings.AppSettings("Application Name"))
End Sub

— 書き込みボタン
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim asm As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
Dim appConfigPath As String
appConfigPath = System.IO.Path.GetDirectoryName(asm.Location) + "\Config.exe.config"
Dim doc As System.Xml.XmlDocument = New System.Xml.XmlDocument
doc.Load(appConfigPath)
Dim node As System.Xml.XmlNode = doc("configuration")("appSettings")

Dim n As System.Xml.XmlNode
For Each n In doc("configuration")("appSettings")
If n.Name = "add" Then
If n.Attributes.GetNamedItem("key").Value = "Application Name" Then
n.Attributes.GetNamedItem("value").Value = Me.Text
End If
End If
Next

Dim newNode As System.Xml.XmlElement = doc.CreateElement("add")
newNode.SetAttribute("key", "Form Size")
newNode.SetAttribute("value", Me.Width & "," & Me.Height)
node.AppendChild(newNode)
doc.Save(appConfigPath)
End Sub