Library tutorials & articles

Files and Folders

INI files

Before the occurrence of the registry in 32 bit Windows (Windows 95), if you wanted to save any form of application settings, such as the initial window size, you used INI files. Most applications store this information in the Windows registry now, however, you may find it easier to use INI files for now. One advantage of using INI files, is you can easily edit the files manually and also, any settings can easily be removed. INI files use the following structure:

[SectionName]
KeyName1 = KeyValue
KeyName2 = KeyValue

For an example of an INI files, look at the Win.ini file stored in your windows directory. The following code shows how to read and write to an INI file. Create a new project and go Projects | Add Module to add a new module.

Then add the following code.

'// VB Web Code Example
'// www.vbweb.co.uk

' DLL declarations
Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

'// Functions
Function GetFromINI(sSection As String, sKey As String, sDefault As String, sIniFile As String)
    Dim sBuffer As String, lRet As Long
    ' Fill String with 255 spaces
    sBuffer = String$(255, 0)
    ' Call DLL
    lRet = GetPrivateProfileString(sSection, sKey, "", sBuffer, Len(sBuffer), sIniFile)
    If lRet = 0 Then
        ' DLL failed, save default
        If sDefault <> "" Then AddToINI sSection, sKey, sDefault, sIniFile
        GetFromINI = sDefault
    Else
        ' DLL successful
        ' return string
        GetFromINI = Left(sBuffer, InStr(sBuffer, Chr(0)) - 1)
    End If
End Function

'// Returns True if successful. If section does not
'// exist it creates it.
Function AddToINI(sSection As String, sKey As String, sValue As String, sIniFile As String) As Boolean
    Dim lRet As Long
    ' Call DLL
    lRet = WritePrivateProfileString(sSection, sKey, sValue, sIniFile)
    AddToINI = (lRet)
End Function

You can then use this code to write and read from the ini files.

Comments

  1. 09 Nov 2005 at 01:04
    Hi all,
    I am a new beginner of Visual basic 6. Even though i read James's article, i don't know how to create a project and add his code as a new module.
    Could you please show me how to create 1 project has 1 command button and 1 optionbox only? Also how to add James' s code to that project?Thanks for your time and understanding.
    PS: tieungao35@yahoo.com
  2. 26 Sep 2005 at 18:17
    Hello,

    the article of James is not state of the art.
    To import win32 functions is not the way how you should work with the .NET framework. With a little bit pation you can write a own managed code assemby for INI Files.

    Tom
  3. 07 Jul 2005 at 22:23

    I am using deppfreeze in my internet cafe.This program protects hard drive from every changes and does not allow save games.When computer restarted all saves dissapear from hard drive.I know the games save directories and i need visual basic code that copies all files in directory to server.Code must overwrite and must include subdirectories.As msdos command does :


    xcopy C:\Program Files\Call of Duty\Main\save*.*  \server\saves\call of duty /e/y


    (/e/y parameter is for overwrite and include subdirectory)


    Can anyone help me.Thnx.

  4. 20 Mar 2005 at 21:19
    do you a source code of hing folders???
  5. 20 Mar 2005 at 21:07
    can anybody plz help me i want to have a sourcec code of hidng folders in windows directory.thanks
  6. 24 Feb 2005 at 15:12

    I've been able to follow your examples regarding making directories and renaming.


    I would like to know two more things.


    One: How do I check for a directory?
    Reason: I am developing a database that will need to check for a directory's existance using the current month's name as its lable. If the a directory does not exist with the current month's name - I will have code automatically create a new directory using the current month's name each time a new calendar month begins and identified by the system.


    Two: Can I use wild cards? Basically can I do the following in VBA -


    FileCopy "C:\Foldername*.", "D:\DifferentFoldername*."


    Thanks


    Greg

  7. 13 Dec 2004 at 09:41
    Ok, for those of us who are begining like me, I was able to find my mistake for number 2.  I simply had the syntax mixed up for the Dir function..I thought I could use it as a variable name...I was wrong.

    Dim fp ' declare my variable that I want to use for the directory

    fp = Dir("C:\work\venturaModify\06144") ' Set the variable equal to "a directory. This is where I am trying to make the user select this path, instead of me hardcoding it in.

    ...further into the "FileSearch" function I set the directory like this:

    .LookIn = Dir(fp)

    ...I am still struggling with my forms..I went through the tutorial by James, but haven't found anything online about selecting a Path via a form I can create.

    .-j
  8. 13 Dec 2004 at 08:07
    I'd like to allow a user to select a directory path, then parse a bunch of files in that directory. I have the parsing part down, and I can hard code a directory in just fine, however I need to enable people to select a directory in order to make this mini-app useful.

    ...My issue is two fold,

    1. I need direction as to how to create a form in VB that will give users the ability to select a directoy. (I am new to vb, and not sure where to start. I am not asking anyone to do it for me, but if you could point me to a tutorial, example online that would help it'd be great.

    2.  I am using the ".LookIn = """ command to specify a directory right now. I am having problems specifying a variable (E.g. Dir = "C:/folder/subfolder", then .LookIn = Dir) doesn't seem to work) Any ideas as to why?
  9. 06 Apr 2004 at 19:58

    Hello there...


    I have problems manipulating very big text files (I´m talking about files around 10 MB of plain text!!) and I have  to find certain kind of words in the document (parse).


    The files have a columns format (like vectors):


    Var1      Var2      Var3     ....   Var10
    Value1   Value1   Value1  ....   Value1
    Value2   Value2   Value2  ....   Value2
    Value3   Value3   Value3  ....   Value3
    ...          ...          ...                ...
    ValueN   ValueN   ValueN  ....   ValueN


    ///--------Comment line-----///


    Var11      Var12      Var13     ....   Var20
    and so on...


    I can calculate the size of the vectors because they have the same size, but I don't know how many "keywords" are because they vary file to file...


    Currently I'm reading the files Line by Line... and it's like hell!!
    I found in a book that I can open the file using the Random Method and the Get and Seek functions but I don't know exactly how to use them.


    Thanks in advance!!

  10. 27 Mar 2004 at 07:24

    can anyone recommend a book or tutorial about hiding a file and folder..............

  11. 27 Mar 2004 at 07:06

    i want to have a tutorial of hiding folders or files if there is one...........................

  12. 05 Mar 2004 at 15:43
    Function GetFileList(FileSpec As String) As Variant
    '   Returns an array of filenames that match FileSpec
    '   If no matching files are found, it returns False

       Dim FileArray() As Variant
       Dim FileCount As Integer
       Dim FileName As String
       
       On Error GoTo NoFilesFound

       FileCount = 0
       FileName = Dir(FileSpec)
       If FileName = "" Then GoTo NoFilesFound
       
    '   Loop until no more matching files are found
       Do While FileName <> ""
           FileCount = FileCount + 1
           ReDim Preserve FileArray(1 To FileCount)
           FileArray(FileCount) = FileName
           FileName = Dir()
       Loop
       GetFileList = FileArray
       Exit Function

    '   Error handler
    NoFilesFound:
       GetFileList = False
    End Function
  13. 25 Feb 2004 at 13:43

    I'd like to know how to get a list of files that are in a folder and put the file names into an array.

  14. 25 May 2003 at 12:33
    It's too Late.i know .
    If you really want to hide some files and FOLDERS from your computer, other than do it yourself....you could download a Wonderful program from PCMagic's MAGIC FOLDER....
  15. 06 Apr 2003 at 09:33
    dear all,
    i am soorya need some API samples in VB to Hide Files and folders for security purpose.
    most of the samples i get from pscode.com is useless...

    can any one pls. let me some to

    soorya@vsnl.com

    thanks in advance
    soorya
  16. 27 Mar 2003 at 19:10

    You're right, but it's not what I meant.


    I wanted a way of finding what the Filenumber of a particular file was.


    Doesn't matter now though, I found a way around it and have finished the program entirely.


    lol, thanks anyway

  17. 27 Mar 2003 at 16:16

    I think nFileNum is just a variable for the file number, for another file you'd have to use something else. I'm probably wrong though.

  18. 27 Mar 2003 at 16:05

    First you need the filesize, I forget how to find it so we'll assume it's 20 bytes. ^_^; Then you'll need enough memory to hold it all. In this case to make things simple, we'll output the data to another file.


    offset = 20
    offset2 = 1
    do while offset >0
    get #1, offset, variable
    put #2, offset2, variable
    offset = offset - 1
    offset2 = offset2 + 1
    loop


    Something along those lines should work, I'm a little rusty. I just stared a week or two ago.

  19. 06 Mar 2003 at 12:50

    If the program has multiple files open at the same time, how do I find the files nFileNum identifier so I can close a particular one?


    Is there a piece of code that can return this?


    I have the names and addresses of the files stored in an array, might be of a use.


    Thanks buddeh, the rest of it really helped

  20. 28 Sep 2002 at 13:29

    After all the search I think I found something very complete, "friendly" speech, and lots of examples.


    This is what I look in a book/tutorial or whatever.


    Congrats to the author


    LMDG

  21. 14 Sep 2002 at 13:47

    Hello


    I would like to know, how to read a file in binary mode, the other
    way around ( from the end to the beginning of the file).


    Thanks in advance
    Ignacio Cemeli
    ignasicemeli@hotmail.com



  22. 03 Sep 2002 at 15:55

    This tutorial about Files and Directories are Especially useful.But for the sake of Security ,hiding a file or a Folder is a Must.How Could we do it From VB application.Any useful API's dedicated for it....
     Anybody help Please..

  23. 01 Jan 1999 at 00:00

    This thread is for discussions of Files and Folders.

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback