thongkorn โพสต์ 2017-10-21 20:21:07

[VB.NET] วิธีการจัดเก็บ และดึงข้อมูลที่กำหนดเองจาก app.config

http://www.g2gnet.com/webboard/images/vbnet/AppConfig.png
บทความนี้อธิบายถึงวิธีการเก็บข้อมูลแบบกำหนดเองในแฟ้มการตั้งค่าคอนฟิก (.config ของโปรแกรม) ที่คุณสามารถเรียกดูได้ในภายหลัง ในระหว่างการรันไทม์ของแอพพลิเคชันที่เกี่ยวข้อง มีประโยชน์เมื่อคุณต้องกำหนดข้อมูลที่เกี่ยวข้องกับแอพพลิเคชัน (แปลจาก Microsoft 5555+ ... https://support.microsoft.com/th-th/help/815786/how-to-store-and-retrieve-custom-information-from-an-application-confi)<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
    <add key="Server" value="(local)" />
    <add key="Database" value="G2GNETDB" />
    <add key="uid" value="admin" />
    <add key="pwd" value="admin" />
    <add key="providerType" value="Sql" />
    <add key="databaseVersion" value="MSSQL2016" />
</appSettings>
</configuration>รูปร่างหน้าตาของไฟล์ app.config ก็จะอยู่ในรูปแบบของ XML (eXtensible Markup Language) อีกแล้วครับท่าน ...
http://www.g2gnet.com/webboard/images/vbnet/appconfigref.png
อันดับแรกต้องอ้างอิง Library หรือ การเรียกใช้ Reference --> System.Configuration
      '<?xml version="1.0" encoding="utf-8"?>
      '<configuration>
      '<appSettings>
      '<add key="Server" value="(local)" />
      '<add key="Database" value="G2GNETDB" />
      '<add key="uid" value="admin" />
      '<add key="pwd" value="admin" />
      '<add key="providerType" value="Sql" />
      '<add key="databaseVersion" value="MSSQL2016" />
      '</appSettings>
      '</configuration>
      Try
            Dim reader As New System.Configuration.AppSettingsReader
            txtServer.Text = reader.GetValue("server", GetType(String))
            txtDatabase.Text = reader.GetValue("database", GetType(String))
            txtUID.Text = reader.GetValue("uid", GetType(String))
            txtPwd.Text = reader.GetValue("pwd", GetType(String))
            btnSave.Enabled = True

      Catch ex As Exception
            MessageBox.Show(ex.Message, "Read Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
      End Tryมีอยู่หลายวิธีในการเรียกข้อมูลออกมาจาก app.config สำหรับตัวอย่างนี้แอดมินใช้ Class AppSettingsReader เพื่อเลือกการอ่านเฉพาะค่าออกมาเลย ... (https://msdn.microsoft.com/en-us/library/system.configuration.appsettingsreader(v=vs.110).aspx)
      Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
      Dim settings As KeyValueConfigurationCollection = config.AppSettings.Settings
      Try
            '// update SaveBeforeExit
            settings("server").Value = txtServer.Text
            settings("database").Value = txtDatabase.Text
            settings("uid").Value = txtUID.Text
            settings("pwd").Value = txtPwd.Text
            '//save the file
            config.Save(ConfigurationSaveMode.Modified)
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name)

            MessageBox.Show("Update Setting.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Information)
            btnSave.Enabled = False

      Catch ex As Exception
            MessageBox.Show(ex.Message)
      End Tryสำหรับการ Save ข้อมูลกลับเข้าไปใน app.config

IMPORTANT - สำคัญเชียวน่ะจะบอกให้
เมื่อเราสั่งทดสอบโปรแกรมด้วยการกด F5 หากเกิดการเปลี่ยนแปลงใดๆของข้อมูล เราจะมองไม่เห็น เพราะว่าตำแหน่งของไฟล์ Execute กับไฟล์ app.config อยู่คนละตำแหน่งกัน ... การใช้วิธีนี้ต้อง Build Project ก่อน จากนั้น App.Config มันจะถูกคัดลอกนำไปไว้ยังโฟลเดอร์ Debug/Release (ขึ้นกับว่าเราไปกำหนดให้ Execute ที่ไหน) จากนั้นมันก็สร้าง ชื่อโปรเจค.exe.config เช่นตัวอย่างนี้คือ MyAppConfig ... เราจะรันเพื่อให้สามารถเปลี่ยนแปลงข้อมูลได้ที่นี่
มาดูโค้ดฉบับเต็ม ...
' / --------------------------------------------------------------------------------
' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
' / eMail : thongkorn@hotmail.com
' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
' / Facebook: https://www.facebook.com/commonindy (Worldwide)
' /
' / Purpose: Using app.config for user defined @runtime parameters.
' / Microsoft Visual Basic .NET (2010)
' /
' / This is open source code under @CopyLeft by Thongkorn Tubtimkrob.
' / You can modify and/or distribute without to inform the developer.
' / --------------------------------------------------------------------------------
Imports System.Configuration

Public Class frmConfig
    Private Sub btnLoad_Click(sender As System.Object, e As System.EventArgs) Handles btnLoad.Click
      '<?xml version="1.0" encoding="utf-8"?>
      '<configuration>
      '<appSettings>
      '<add key="Server" value="(local)" />
      '<add key="Database" value="G2GNETDB" />
      '<add key="uid" value="admin" />
      '<add key="pwd" value="admin" />
      '<add key="providerType" value="Sql" />
      '<add key="databaseVersion" value="MSSQL2016" />
      '</appSettings>
      '</configuration>
      Try
            Dim reader As New System.Configuration.AppSettingsReader
            txtServer.Text = reader.GetValue("server", GetType(String))
            txtDatabase.Text = reader.GetValue("database", GetType(String))
            txtUID.Text = reader.GetValue("uid", GetType(String))
            txtPwd.Text = reader.GetValue("pwd", GetType(String))
            btnSave.Enabled = True

      Catch ex As Exception
            MessageBox.Show(ex.Message, "Read Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
      End Try

    End Sub

    Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
      Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
      Dim settings As KeyValueConfigurationCollection = config.AppSettings.Settings
      Try
            '// update SaveBeforeExit
            settings("server").Value = txtServer.Text
            settings("database").Value = txtDatabase.Text
            settings("uid").Value = txtUID.Text
            settings("pwd").Value = txtPwd.Text
            '//save the file
            config.Save(ConfigurationSaveMode.Modified)
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name)
            '// Or use sub program from MSDN.
            '//AddUpdateAppSettings("database", txtDatabase.Text)

            MessageBox.Show("Update Setting.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Information)
            btnSave.Enabled = False

      Catch ex As Exception
            MessageBox.Show(ex.Message)
      End Try
    End Sub

    '// If you want to learn more.
    '// https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings(v=vs.110).aspx
    Sub AddUpdateAppSettings(key As String, value As String)
      Try
            Dim configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            Dim settings = configFile.AppSettings.Settings
            If IsNothing(settings(key)) Then
                settings.Add(key, value)
            Else
                settings(key).Value = value
            End If
            configFile.Save(ConfigurationSaveMode.Modified)
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name)
      Catch e As ConfigurationErrorsException
            MessageBox.Show("Error writing app settings: " & vbCrLf & e.Message)
      End Try
    End Sub

    Private Sub frmConfig_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
      btnSave.Enabled = False
    End Sub

    Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
      Me.Close()
    End Sub

    Private Sub frmConfig_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      Me.Dispose()
      Application.Exit()
    End Sub

End Classดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010)

g2gsoftuser โพสต์ 2022-10-25 17:20:45

ขอบคุณครับ

MMEE007 โพสต์ 2022-12-11 21:12:32

ขอบพระคุณคัพ อาจารย์:loveliness::loveliness::loveliness:
หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] วิธีการจัดเก็บ และดึงข้อมูลที่กำหนดเองจาก app.config