Solved

vb.net read ini file

Posted on 2004-08-12
27
63,233 Views
Last Modified: 2011-10-03
I have an ini file that I would like to read using .net

I am creating a program that will work off the ini file. Can anyone show me how to program for it, or better yet if ini is not the way to go show me another example that would be good......


0
Comment
Question by:bear23
  • 5
  • 4
  • 4
  • +7
27 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 11786214
Have a look at http://www.utmag.com/May2003/Page59.asp

You can download the demo from the last page ( http://www.utmag.com/May2003/EricMoreau.zip )
0
 
LVL 3

Accepted Solution

by:
aflat362 earned 35 total points
ID: 11786658
Microsoft wants people to use the registry instead of INI files.

But Here's a class for reading ini files (not mine, found it somewhere) - at bottom

Use it like this

        objIniFile = New IniFile("C:\AscentAutoImportXMLGenerator\setup.ini")

objIniFile.GetString("setup", "FileDirectory", "")

where ini file looks like

[setup]
FileDirectory=whatever

'Utility Class for Reading INI Files
Public Class IniFile
    ' API functions
    Private Declare Ansi Function GetPrivateProfileString _
      Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _
      (ByVal lpApplicationName As String, _
      ByVal lpKeyName As String, ByVal lpDefault As String, _
      ByVal lpReturnedString As System.Text.StringBuilder, _
      ByVal nSize As Integer, ByVal lpFileName As String) _
      As Integer
    Private Declare Ansi Function WritePrivateProfileString _
      Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _
      (ByVal lpApplicationName As String, _
      ByVal lpKeyName As String, ByVal lpString As String, _
      ByVal lpFileName As String) As Integer
    Private Declare Ansi Function GetPrivateProfileInt _
      Lib "kernel32.dll" Alias "GetPrivateProfileIntA" _
      (ByVal lpApplicationName As String, _
      ByVal lpKeyName As String, ByVal nDefault As Integer, _
      ByVal lpFileName As String) As Integer
    Private Declare Ansi Function FlushPrivateProfileString _
      Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _
      (ByVal lpApplicationName As Integer, _
      ByVal lpKeyName As Integer, ByVal lpString As Integer, _
      ByVal lpFileName As String) As Integer
    Dim strFilename As String

    ' Constructor, accepting a filename
    Public Sub New(ByVal Filename As String)
        strFilename = Filename
    End Sub

    ' Read-only filename property
    ReadOnly Property FileName() As String
        Get
            Return strFilename
        End Get
    End Property

    Public Function GetString(ByVal Section As String, _
      ByVal Key As String, ByVal [Default] As String) As String
        ' Returns a string from your INI file
        Dim intCharCount As Integer
        Dim objResult As New System.Text.StringBuilder(256)
        intCharCount = GetPrivateProfileString(Section, Key, _
           [Default], objResult, objResult.Capacity, strFilename)
        If intCharCount > 0 Then GetString = _
           Left(objResult.ToString, intCharCount)
    End Function

    Public Function GetInteger(ByVal Section As String, _
      ByVal Key As String, ByVal [Default] As Integer) As Integer
        ' Returns an integer from your INI file
        Return GetPrivateProfileInt(Section, Key, _
           [Default], strFilename)
    End Function

    Public Function GetBoolean(ByVal Section As String, _
      ByVal Key As String, ByVal [Default] As Boolean) As Boolean
        ' Returns a boolean from your INI file
        Return (GetPrivateProfileInt(Section, Key, _
           CInt([Default]), strFilename) = 1)
    End Function

    Public Sub WriteString(ByVal Section As String, _
      ByVal Key As String, ByVal Value As String)
        ' Writes a string to your INI file
        WritePrivateProfileString(Section, Key, Value, strFilename)
        Flush()
    End Sub

    Public Sub WriteInteger(ByVal Section As String, _
      ByVal Key As String, ByVal Value As Integer)
        ' Writes an integer to your INI file
        WriteString(Section, Key, CStr(Value))
        Flush()
    End Sub

    Public Sub WriteBoolean(ByVal Section As String, _
      ByVal Key As String, ByVal Value As Boolean)
        ' Writes a boolean to your INI file
        WriteString(Section, Key, CStr(CInt(Value)))
        Flush()
    End Sub

    Private Sub Flush()
        ' Stores all the cached changes to your INI file
        FlushPrivateProfileString(0, 0, 0, strFilename)
    End Sub

End Class


0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 11786683
>>Microsoft wants people to use the registry instead of INI files.

That was in the VB5/6 era. Now Microsoft wants people to use XML files.
0
 

Author Comment

by:bear23
ID: 11787593
ok, I am using the

  objIniFile = New IniFile("C:\AscentAutoImportXMLGenerator\setup.ini")

objIniFile.GetString("setup", "FileDirectory", "")


good idea, but how can I loop through and pull each line for that 1 key meaning

exe

[setup]
filedirectory = whatever
file2 = hello world
file3 = goodbye
[settings]
config=3


and the program would loop through until it reached the settings key
0
 

Expert Comment

by:Hooyer
ID: 11787700
I'm using the INIReade class from Metalis.org. go to http://www.mentalis.org/soft/class.qpx?id=6 for a download.
0
 

Author Comment

by:bear23
ID: 11787855
the other problem I face though is this

[setup]
'file for dfsdfs
filedirectory = whatever
'this file say hello
file2 = hello world
'this file says goodbye
file3 = goodbye
[settings]
config=3

notice the comments I need to have so now what??? the code must look at the keys only
0
 

Author Comment

by:bear23
ID: 11787866
or am I better off reading out of a database??? I jsut though that reading from a INI file would be quicker??? What do you think


0
 
LVL 3

Expert Comment

by:aflat362
ID: 11789104
>> how can I loop through and pull each line for that 1 key meaning

Simple
(check the syntax - I usually program in java)

i = 1

Do While i < 5
   objIniFile.GetString("setup", "FileDirectory" & i, "")
Loop

will read

FileDirectory1
FileDirectory2
FileDirectory3 . . . And so on.

Your question about reading the database.  .  .

I guess it depends.  If you only have a few things to read and the data won't change hardly ever an INI file might be better suited.

You just have to weigh your options.
0
 

Author Comment

by:bear23
ID: 11790238
can't get it to work, I will not know what the keys are, I just need to have it look for keys and then enter the values.....


the reason is I want to be able to write this program and never have to come back to it. All I would have to do is add new keys under the [setup] and the program would read it. Understand?????


[setup]
'file for dfsdfs
filedirectory = whatever
'this file say hello
file2 = hello world
'this file says goodbye
file3 = goodbye
[settings]
config=3


so it would grab

filedirectory = whatever
file2 = hello world
file3 = goodbye



but lets say I go in the future and add a file23 the program will read it ok. Understand or am I better off having either an xml file or a database file that looks at record 1 and reads until it reaches the end of the record count.


any idea????
0
 
LVL 3

Expert Comment

by:aflat362
ID: 11792639
Whatever works, works.

If your INI file works for you thats proabably fine.

Whether you want to use an INI file or an XML or a database is up to you (or your organization if you are a corporate slave like myself - ask around if you're not sure)

Like I said, you have to look at the strengths and weaknesses of each storage option.  

The INI file provides key, value pairs grouped off by sections.  

An XML file provides a way to describe information hierarchically as well as multiple attributes per object.  

A database provides the most poweras you can store large amounts of data in a relational structure and access it quickly using the SQL langauge.

You have to pick the right tool for the right job.

From what I've seen of your program (very llittle) It sounds like you are storing values on the fly and wanting to read them back later.  THis does sound sort of like a database to me, but if your data is simple enough, something like an ini file would work.

You know, you could go even less structured and use a flat file - just one record per line.
when you want to get some data you read every single line and pull the one you recognize in your logic.  Whatever works.
0
 

Expert Comment

by:Hooyer
ID: 11794776
The library i mentioned will just ignore the commented lines.

Use the following code to read a variable number of key's into an array

    Private INI As IniReader
    Private Files As New ArrayList()
    Private Directory as string
    Private sTemp as String
    private i as integer

    INI = New IniReader("yourfile.ini")
    Directory = INI.ReadString("setup", "filedirectory")
    i=1

        Do
            Try
                sTemp = INI.ReadString("setup", "file" & Trim(Str(i)))
            Catch
                Exit Do
            End Try
            If sTemp <> "" Then
                Files.Add(sTemp)
                i = i + 1
            Else
                Exit Do
            End If
        Loop
0
 
LVL 8

Expert Comment

by:bman9111
ID: 11795043
better yet use an xml, it is a lot better and quick

I would do something like this:


 Dim filetoread As DataSet = New DataSet
filetoread .ReadXml((Application.StartupPath) & "\yourxmlfilename.xml", XmlReadMode.Auto)
textbox1.Text = filetoread .Tables("table1").Rows(a).Item("Field1")

have the xml look like this:

?xml version="1.0" standalone="yes"?>
<dataroot>
  <Table1>
    <Field1>whatever you want to type</field1>
  </Table1>

</dataroot>

what will happen is the text box will show that first field then if you put more in you can do a do loop.


0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 3

Expert Comment

by:aflat362
ID: 12005021
I believe I answered his question in my first post.  You could give points to Hooyer and bear23 also as they spent some time on this also.
0
 
LVL 8

Expert Comment

by:toddhd
ID: 12124834
Just FYI, there is a simple, open source class to handle this here:
http://www.codeproject.com/vb/net/VbNetClassIniFile.asp

And a similar offer for C++ folks:
http://www.codeproject.com/useritems/CIniFile.asp
0
 
LVL 3

Expert Comment

by:aflat362
ID: 13382286
I had created 2 accounts, one for programming at home and one for programming at work

If this is against the rules - the aflat362home account can be deleted.
0
 

Expert Comment

by:mudharan
ID: 13895935
Usage of XML is most recommended way instead of using ini.
Its easier and understandable.

Looping thro a particular node to get values are easier when xml is used. for example
<INCLUSION_LIST>
     <INCLUDE>User1</INCLUDE>
     <INCLUDE>User2</INCLUDE>
     <INCLUDE>User3</INCLUDE>
</INCLUSION_LIST>
0
 

Expert Comment

by:rayfusion
ID: 14311217
Huh
0
 

Expert Comment

by:mudharan
ID: 14311589
Or instead of using XML you could use the App.Config and System.Configuration would be a better approach using OOP.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="environment">
      <section name="development" type="System.Configuration.NameValueSectionHandler, System,Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <section name="qa" type="System.Configuration.NameValueSectionHandler, System,Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <section name="production" type="System.Configuration.NameValueSectionHandler, System,Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="environment" value="development" />
    <add key="userprofile" value="c:\myapp\profiles\" />
    <add key="layouts" value="c:\common\layout\" />
  </appSettings>
  <environment>
    <development>
      <add key="apptitlesuffix" value="Dev" />
      <add key="dbserver" value="server1" />
      <add key="db" value="dev_db" />
    </development>
    <qa>
      <add key="apptitlesuffix" value="QA" />
      <add key="dbserver" value="server2" />
      <add key="db" value="qa_db" />
    </qa>
    <production>
      <add key="apptitlesuffix" value="Prod" />
      <add key="dbserver" value="server3" />
      <add key="db" value="prod_db" />
    </production>
  </environment>
</configuration>


Create a class like below

using System;
using System.Configuration;
using System.Collections.Specialized;

public class Configuration {
  string _environment;
  string _profile;
  string _layout;
 
  NameValueCollection _environmentConfig;

  public Configuration() {
    _environment = ConfigurationSettings.AppSettings["environment"];
    _profile = ConfigurationSettings.AppSettings["userprofile"];
    _layout = ConfigurationSettings.AppSettings["gridlayout"];
   
    _environmentConfig = (NameValueCollection)ConfigurationSettings.GetConfig("environment/" + _environment);

  }

  public string Environment{
    get{ return _environment; }
  }

  public string ProfilePath{
    get{ return _profile; }
  }

  public string LayoutPath{
    get{ return _layout;}
  }
 
  public string ApplicationTitleSuffix{
    get{ return _environmentConfig["apptitlesuffix"]; }
  }
 
  public string DatabaseServer{
    get{ return _environmentConfig["dbserver"]; }
  }
 
  public string Database{
    get{ return _environmentConfig["db"]; }
  }
 
}

this example is in C# and you could replace it with vb.net syntax to run your app.
Hope it was of some use.
0
 
LVL 1

Expert Comment

by:davo007
ID: 14783570
Is there any reason you don't want to use the registry option? It seems to be a lot less trouble than the ini file option.  And depending on how many settings you need, could be less coding than the above option.

I tried to get an ini file to work for a vb .net proggy i was doing, spend ages trying to get it to work....plus there was stacks of code....gave up and tried registry entries....was much easier and a lot less code compared to the ini file....
0
 

Expert Comment

by:mudharan
ID: 14783732
A config file (app.config) like the one below could be easily parsed in two lines of code

<code>
dsn = ConfigurationSettings.AppSettings("datasource")
db = ConfigurationSettings.AppSettings("database")
</code>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <appSettings>
            <add key="datasource" value="sqlserver1" />
            <add key="database" value="db1" />
      </appSettings>
</configuration>

0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 14783756
You don't want to mess the registry and how do you deploy values (like the ConnectionString) to the registry when you have to change your server ?
0
 

Expert Comment

by:DingleBerry9876543210
ID: 14783764
davo007

If you had your registry get corrupt from installing an application you would not be asking that. Microsoft is moving far away from telling programmers to have their applications use the registry due to the inherent problem of having so many programs playing around so close to the system settings (nothing but problems), they are encouraging the use of an xml equivalent of the ini.

Dingle
0
 
LVL 8

Expert Comment

by:bman9111
ID: 14783769
one problem for me when using the registry is that when xp accounts were set to user profile it won't work. I had to go to each computer and give rights to the registry that my program was trying to access, being that user profile doesn't give user rights to registry..

0
 

Expert Comment

by:mudharan
ID: 14783876
I mean

dsn = ConfigurationSettings.AppSettings("datasource")
db = ConfigurationSettings.AppSettings("database")

Above code will get values to corresponding variables from config file (app.config) like the one below. Including config sections and section groups you could have complex config files and this could be deployed along with binaries. Registry entries are age old fashion.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
     <appSettings>
          <add key="datasource" value="sqlserver1" />
          <add key="database" value="db1" />
     </appSettings>
</configuration>
0
 
LVL 1

Expert Comment

by:davo007
ID: 14784703
I see your point, the xml way does look better...however, can you still write the settings in the same fashion??
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This is an explanation of a simple data model to help parse a JSON feed
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now