【问题标题】:Reading/Writing INI w/ variable Section Name读/写带有可变节名称的 INI
【发布时间】:2013-05-23 19:11:34
【问题描述】:

大家下午好-

我正在读/写一个由第三方创建和管理的外部文件,该第三方使用 .INI 结构化文件作为其脚本语言。我有一个运行良好的包装器,但是,部分名称是静态的,末尾有一个唯一编号([GENERAL-1]),因此您不止一次执行相同的任务。我正在使用带有 VS2008 的 VB.NET。

我下面的代码可以成功地从硬编码的部分读取密钥,但我希望密钥是通用的。

INI

test.ini
[GENERAL-1]
SUPPRESSTASKERRORS=Y
TASKERRORSENDJOB=Y

代码:

Declare Function GetPrivateProfileString Lib "kernel32.dll" Alias    
"GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As  
String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As   
Long, ByVal lpFileName As String) As Long

Declare Function WriteProfileString Lib "kernel32.dll" Alias 
"WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As   
String, ByVal lpString As String, ByVal lpFileName As String) As Long



' Read INI file
    Dim uname As String ' receives the value read from the INI file
    Dim slength As Long ' receives length of the returned string
    Dim OriginalMJB As String = "c:\test\test.ini"
    uname = Space(1024)

slength = GetPrivateProfileString("General-1", "SUPPRESSTASKERRORS", "anonymous", 
uname, 1024, OriginalMJB)

请注意上面的 General-1,如果我将值硬编码为 -1,我可以毫无问题地读取输入的 .ini 文件。关于如何获取和使用连字符左侧的值有什么想法吗?

感谢任何帮助!

--乔治

【问题讨论】:

  • 这不行吗? Dim section As String = "General" slength = GetPrivateProfileString(section & "-1", "SUPPRESSTASKERRORS", "anonymous", uname, 1024, OriginalMJB)
  • 您不能创建一个循环来调用 General-1、General-2 等吗?您可以在前 1 或 2 个参数中使用 NULLS 调用 Getprivate... 以获取当前内容的列表。请参阅 MSDN 文档。
  • 你是说你想要一个可以用不同后缀值调用的函数?
  • 连字符 (-1) 可以是任何值。连字符只是使该部分唯一,因此您可以拥有多个具有相同名称的部分,例如 IMPORT-1 和 IMPORT-2 然后被视为两个单独的部分。我真的希望 -1 是可变的,其中一个脚本可能是 GENERAL-1 和另一个 GENERAL-2.. 有意义吗?
  • 也许可以使用正则表达式来查看该部分的开头??

标签: vb.net visual-studio-2008 ini


【解决方案1】:

这是一种方法。从这里您应该能够使 SectionNo 等于您想要的特定部分。

Dim section As String = "General"
Dim SectionNo as String = "-"
Dim Number as Integer = 1
SectionNo += Number.ToString
slength = GetPrivateProfileString(section + SectionNo, "SUPPRESSTASKERRORS", "anonymous", uname, 1024, OriginalMJB)

这里有几个选项

    Dim SectionName As String = "General-1"
    Dim SectionCategorie As String = ""
    Dim Section As String = ""

    'Using Split - It returns an array so you can load the results into an array   
    'or just call it and load the specific index each time.
    SectionCategorie = Split(SectionName, "-")(0)
    Section = Split(SectionName, "-")(1)

    'Using Substring

    SectionCategorie = SectionName.Substring(0, SectionName.IndexOf("-"))
    Section = SectionName.Substring(SectionName.IndexOf("-") + 1)

【讨论】:

  • 连字符后的“数字”或值是可变的,可以是数字或alhpa字符。试图让左/右表达式起作用,以便我可以解析部分名称并且只对连字符取值..
  • 我添加了几个选项供您查看
猜你喜欢
  • 2015-02-17
  • 1970-01-01
  • 2014-08-12
  • 2014-04-14
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 2012-10-09
相关资源
最近更新 更多