Link to home
Start Free TrialLog in
Avatar of bear23
bear23

asked on

vb.net read ini file

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......


Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

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 )
ASKER CERTIFIED SOLUTION
Avatar of aflat362
aflat362

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>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.
Avatar of bear23
bear23

ASKER

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
I'm using the INIReade class from Metalis.org. go to http://www.mentalis.org/soft/class.qpx?id=6 for a download.
Avatar of bear23

ASKER

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
Avatar of bear23

ASKER

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


>> 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.
Avatar of bear23

ASKER

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????
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.
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
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.


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.
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
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.
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>
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.
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....
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>

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 ?
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
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..

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>
I see your point, the xml way does look better...however, can you still write the settings in the same fashion??