Jump to content

Retrieve "Key" name from "Value" name in .ini files


Recommended Posts

Hej Guys.

Thought I would share a cool thing I found out earlier today. From time to time I use .ini files to make things a bit easier and sometimes I need to get the key name from a section, based on what value it has.

A good example:

DiskConfig1=1. Full Disk


Lets say that our user has chosen 1. Full Disk from a GUICtrlCombo. The value is a friendly name instead of DiskConfig1, simply because our user might not know which DiskConfig# does which. 

We will then use the key to determine how the disk will be setup/partitionened. Now we will need the key-name of 1. Full Disk.

To retrieve it, we will use the following code:

#include <File.au3>


Func Example()

   Global $sValue

   ; Assign data to $sValue
   $sValue = "1. Full Disk"

   ; Call GetKeyFromValue() function and output the result
   MsgBox($MB_SYSTEMMODAL, "Result", GetKeyFromValue(), 0)


Func GetKeyFromValue()
   ; Read all values from ini section
   Local $aSection = IniReadSection(@ScriptDir & "\Settings.ini", "DiskConfigurations")
   If IsArray($aSection) Then
      ; Loop through the array until it finds a match
      For $i = 1 To $aSection[0][0]
         If $aSection[$i][1] = $sValue Then
            ; Return the result
            Return $aSection[$i][0]
      ; Set the error code to 1 if $aSection is not an array

Thats it! Now we would simply have to do:

IniRead(@ScriptDir & "\Settings.ini", GetKeyFromValue(), "Setup", "")


Edited by doestergaard
Link to comment
Share on other sites

I haven't really studied your code, but I'm wondering how you deal with the fact of uniqueness?

Sections names are unique by default, but you have no control over key names or key values, as either could be duplicated many times over in different sections, especially a value, which can occur for many different keys in the same section even.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.


What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)


Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...