Reading and writing an INI file

2019-01-28 17:34发布

问题:

I have been toying with the below script to be able to read settings for use with my HTA (creating a game launcher).

Here is my current HTA:

http://pastebin.com/skTgqs5X

It doesn't quite work, it complains of the WScript object being required. While I understand Echo will not work like that in a HTA I am having trouble modifying the code so it will work. Even just removing all Echo references it still has an issue with objOrgIni on line 200 of the below code (with the WScript references removed):

http://pastebin.com/pGjv4Gh1

I don't even need that level of error checking as the INI will exist etc, I just need a simple way to read from and write to an INI in my scripting. Any help you guys can give me in achieving that would be great, it's a little advanced for me just yet, but I'd love an explanation as to why it fails.

回答1:

There is no easy way to use INI files with VBScript. You'd have to write the functionality yourself or find some existing code that does it.

But do you really need an INI specifically or just a way to save settings? You could just keep all of your settings in a Dictionary object and serialize it as needed.

For example, here are two functions -- LoadSettings and SaveSettings -- that do just that.

Public Function LoadSettings(strFile)

    Set LoadSettings = CreateObject("Scripting.Dictionary")

    Dim strLine, a
    With CreateObject("Scripting.FileSystemObject")
        If Not .FileExists(strFile) Then Exit Function
        With .OpenTextFile(strFile)
            Do Until .AtEndOfStream
                strLine = Trim(.ReadLine())
                If InStr(strLine, "=") > 0 Then
                    a = Split(strLine, "=")
                    LoadSettings.Add a(0), a(1)
                End If
            Loop
        End With
    End With

End Function

Sub SaveSettings(d, strFile)

    With CreateObject("Scripting.FileSystemObject").CreateTextFile(strFile, True)
        Dim k
        For Each k In d
            .WriteLine k & "=" & d(k)
        Next
    End With

End Sub

Imagine you had the following settings file saved at c:\settings.txt:

Count=2
Name=Obama

You'd use the functions above like this:

Const SETTINGS_FILE = "c:\settings.txt"

Dim Settings
Set Settings = LoadSettings(SETTINGS_FILE)

' Show all settings...
WScript.Echo Join(Settings.Keys, ", ")         ' => Count, Name

' Query a setting...
WScript.Echo Settings("Count")                 ' => 2

' Update a setting...
Settings("Count") = Settings("Count") + 1

' Add a setting...
Settings("New") = 1

' Save settings...
SaveSettings Settings, SETTINGS_FILE


标签: vbscript ini hta