George Vaisey
George Vaisey

Reputation: 149

Reading/Writing INI w/ variable Section Name

Good afternoon folks -

I'm working on reading/writing an external file that is created and managed by a 3rd party that uses .INI structured files as its scripting language. I've got a wrapper working pretty well however, the section names are static with a unique number at the end ([GENERAL-1]) so that you have have the same task more than once. I am using VB.NET w/ VS2008.

My code below can successfully read a key from a section that is hardcoded but I'd like the key to be generic.

INI

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

Code:

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)

Notice the General-1 above, if I have the value hardcoded as -1 I can read the input .ini file without a problem. Any thoughts on how I can get and use the value left of the hyphen?

Any help is appreciated!

--George

Upvotes: 0

Views: 1246

Answers (1)

tinstaafl
tinstaafl

Reputation: 6948

Here's one way. From here you should be able to make SectionNo equal the specific section you want.

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)

Here's a couple of options

    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)

Upvotes: 1

Related Questions