读取和写入 INI 文件 [英] Reading and writing an INI file
问题描述
我一直在玩弄下面的脚本,以便能够读取与我的 HTA 一起使用的设置(创建游戏启动器).
I have been toying with the below script to be able to read settings for use with my HTA (creating a game launcher).
这是我目前的 HTA:
Here is my current HTA:
它不太好用,它抱怨需要 WScript
对象.虽然我知道 Echo
在 HTA 中不会像那样工作,但我在修改代码时遇到了麻烦,因此它可以工作.即使只是删除所有 Echo
引用,它仍然存在以下代码第 200 行的 objOrgIni
问题(删除了 WScript
引用):
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):
我什至不需要那种级别的错误检查,因为 INI 将存在等,我只需要一种简单的方法在我的脚本中读取和写入 INI.你们在实现这一目标方面能给我的任何帮助都会很棒,这对我来说还有些先进,但我很想解释一下它为什么会失败.
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.
推荐答案
通过 VBScript 使用 INI 文件没有简单的方法.您必须自己编写功能或找到一些现有的代码来完成它.
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.
但是您真的需要专门的 INI 还是只是一种保存设置的方法?您可以将所有设置保存在 Dictionary
对象中,并根据需要对其进行序列化.
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.
例如,这里有两个函数 -- LoadSettings
和 SaveSettings
-- 就是这样做的.
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
假设您在 c:settings.txt
中保存了以下设置文件:
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
这篇关于读取和写入 INI 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!