VB.NET 中配置文件调用模块

VB.NET · 15 天前 · 49 人浏览

留存下模块代码,下次写代码就不用翻之前的代码了。
模块代码:

    Module ini读写模块
    Private Declare Unicode Function GetPrivateProfileInt Lib "kernel32" Alias "GetPrivateProfileIntW" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal nDefault As Integer, ByVal lpFileName As String) As Integer
    Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    Private Declare Unicode Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringW" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer

    Public Function GetIntFromINI(ByVal sectionName As String, ByVal keyName As String, ByVal defaultValue As Integer, ByVal iniPath As String) As Integer
        GetIntFromINI = GetPrivateProfileInt(sectionName, keyName, defaultValue, iniPath)
    End Function

    Public Function GetStrFromINI(ByVal sectionName As String, ByVal keyName As String, ByVal defaultValue As String, ByVal iniPath As String) As String
        Dim buffer As String
        Dim rc As Integer
        buffer = Space(256)
        rc = GetPrivateProfileString(sectionName, keyName, defaultValue, buffer, buffer.Length, iniPath)
        GetStrFromINI = Left(buffer, InStr(buffer, vbNullChar) - 1)
    End Function

    Public Function WriteStrINI(ByVal sectionName As String, ByVal keyName As String, ByVal setValue As String, ByVal iniPath As String) As Integer
        Dim rc As Integer
        rc = WritePrivateProfileString(sectionName, keyName, setValue, iniPath)
        If rc Then
            rc = 1
        End If
        WriteStrINI = rc
    End Function
End Module

读取:

TextBox1.Text = GetStrFromINI("Config", "A1", "", Application.StartupPath & "\Config.ini")

写入:

WriteStrINI("Config", "B2", TextBox6.Text, Application.StartupPath & "\Config.ini")