Find specific occurance of string in file

ascottk

New member
Joined
Aug 3, 2009
Messages
3
Programming Experience
Beginner
Hi, I'm a newb to programming but not a total stranger (I own VB6, now using vb2008 express). I'm developing a program to tweak the settings of the Thief: Deadly Shadows video game. The tweaker program is designed to load and configuration profiles so the ttlg/T3Ed Guild community can share tweaks with each other and then apply those setting to the game's ini files. A little more info here: [ame=http://www.ttlg.com/forums/showthread.php?t=127954]UNDER DEVELOPMENT - Thief 3 Gold Tweaker - TTLG Forums[/ame] & here are a list of tweaks the tweaker program will apply to the game: [ame=http://www.ttlg.com/forums/showthread.php?t=83801]Thief 3 - Tweak Guide - TTLG Forums[/ame]

Anyway, I managed to load and save the config profiles but I'm stuck on applying those settings to the game's .ini files. The main problem is finding the right string. Thief: Deadly Shadows .ini file has settings for xbox & PC. I only want to change the PC settings in DEFAULT.INI:
VB.NET:
[XboxStartup]
ShowIntroMovies=True
ForceCopyFromHardDrive=False
ShortIntroMovies=d:\content\t3\VideoTextures\eidos-logo.bik; . . . etc.
GameStartFiles=d:\Media\Font12.xpr, . . . etc.

[PCStartup]
ShowIntroMovies=False
ShortIntroMovies=d:\content\t3\VideoTextures\eidos-logo.bik; . . . etc.
I want to change "ShowIntroMovies=False" under the "[PCStartup]" section when the user clicks "Apply Changes" on the main form.

One way I could go about this is to look for "[PCStartup]" hold the line number it's on, then look for the "ShowIntroMovies" string under that line number. There are several instances in the game's .ini files where the same setting exists but they exists under different sections. So how would I find a specific occurrence of a string?
 
There are classes avail;able for download that will work with INI files specifically but it's not hard to write your own code just to deal with them as text. Start by calling File.ReadAllLines to read the entire file into a String array with one line per element. You can then loop through that array until you find the value "[PCStartup]". You can then continue looping until you find the setting of interest. The String.StartsWith method will be helpful here. You can then edit that element. Finally, call File.WriteAllLines to write the modified data back out to the file.
 
I saw a few projects for ini file work but I couldn't make heads or tails out of them BUT I did find something that works for me:
By venomsnake Wire Designs - High Quality Tutorials on PHP, Photoshop, CSS, and more

So I'm treating the tweaker config files differently than the game's ini files. First I bind each control to an application setting, use those settings to a list box:
VB.NET:
With lbxConfigPreview.Items
            .Insert(0, "[T3GoldConfig]")
            .Insert(1, "UserName=" & My.Settings.UserName)
            .Insert(2, "")
            .Insert(3, "[Menu tweaks]")
            .Insert(4, "NoOpeningMov=" & My.Settings.NoOpeningMov)
...etc.
So the user previews the config & saves it if they want.

& I have a separate class for loading back the settings:
VB.NET:
Public Class TDSIniWrite

    Public Shared Function ToBoolean(ByVal value As String) As Boolean

    End Function

    Public Shared Function ToDecimal(ByVal value As String) As Decimal

    End Function
    Public Shared Function SearchForSection(ByVal FileName As String, ByVal SearchString As String) As Boolean
        Dim Section As String = My.Computer.FileSystem.ReadAllText(FileName)
        If InStr(Section, SearchString) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Function SearchValue(ByVal File As String, ByVal Value As String) As String
        Dim SR As New System.IO.StreamReader(File)
        Dim MyString() As String
        While SR.Peek <> -1
            MyString = Strings.Split(SR.ReadLine, "=")
            If MyString(0) = Value Then
                SR.Close()
                Return MyString(1)
            End If
        End While
        SR.Close()
        Return ""
    End Function
End Class

& I call it on the main form:
VB.NET:
With OpenFileDialog1
            .Title = "Please Select a Configuration File"
            .InitialDirectory = FolderBrowserDialog1.SelectedPath
            .Filter = "T3G Tweaker Config(*.t3c)|*.t3c|All Files (*.*)|*.*"
            .RestoreDirectory = True
            .ShowDialog()
            Dim strm As System.IO.Stream = OpenFileDialog1.OpenFile() 'Or 
            My.Settings.UserConfig = OpenFileDialog1.FileName
            If Not (strm Is Nothing) Then
                'insert code to read the file data
                Dim fileContents As String
                fileContents = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
                strm.Close()
                MessageBox.Show(OpenFileDialog1.FileName & " is now the current config")
            End If
        End With
        Try
            BackgroundWorker1.RunWorkerAsync()

            'Import UserName from file
            Dim UserNameString As String = TDSIniWrite.SearchValue(OpenFileDialog1.FileName, "UserName")
            My.Settings.UserName = UserNameString
            My.Settings.MainFormText = "Thief 3 Gold Tweaker - " & My.Settings.UserName

            'Convert NoOpeningMov string to boolean
            Dim NoOpeningMovString As String = TDSIniWrite.SearchValue(OpenFileDialog1.FileName, "NoOpeningMov")
            Dim NoOpeningMovBool As Boolean
            NoOpeningMovBool = Convert.ToBoolean(NoOpeningMovString)
            My.Settings.NoOpeningMov = NoOpeningMovBool
...etc.

& When the user applies the settings it write to the game's ini file:
VB.NET:
'Find ShowIntroMovies under [PCStartup] then changes value
        Dim objIniFile As New IniFileClass(SysDir & "DEFAULT.INI")
        objIniFile.WriteString("PCStartup", "ShowIntroMovies", My.Settings.NoOpeningMov)

& it works!
 
Character encodings (solved)

I'm having a problem with vb's handling of character encodings. When VB writes to a file I get this:
VB.NET:
T_innLoadingQuote0
lang_english 2004-02-29 21:48:00 "On the Last Day, there will be no words...and we will know the face of our betrayer... - Excerpt from the Keeper Book of Days"
lang_french 2004-03-22 07:11:01 "Le Dernier Jour, il n’y aura plus de mots… et nous connaîtrons le visage de celui qui nous a trahis… - Extrait du Livre des Jours des Gardiens"
lang_german 2004-04-13 12:07:07 "Am letzten aller Tage wird es keine Worte geben ... und wir werden das Gesicht des Verräters kennen ... - Aus dem Buch der Tage"
lang_italian 2004-03-25 07:27:36 "Nell'ultimo giorno non ci saranno parole... e noi vedremo il volto del nostro traditore... - Estratto dal Libro dei giorni dei custodi"
When it's supposed to be this:
VB.NET:
T_innLoadingQuote0
lang_english 2004-02-29 21:48:00 "On the Last Day, there will be no words...and we will know the face of our betrayer... - Excerpt from the Keeper Book of Days"
lang_french 2004-03-22 07:11:01 "Le Dernier Jour, il n’y aura plus de mots… et nous connaîtrons le visage de celui qui nous a trahis… - Extrait du Livre des Jours des Gardiens"
lang_german 2004-04-13 12:07:07 "Am letzten aller Tage wird es keine Worte geben ... und wir werden das Gesicht des Verräters kennen ... - Aus dem Buch der Tage"
lang_italian 2004-03-25 07:27:36 "Nell'ultimo giorno non ci saranno parole... e noi vedremo il volto del nostro traditore... - Estratto dal Libro dei giorni dei custodi"
I tried a few different encodings but I'm not sure if any will work or if I have to add an extra argument: My.Computer.FileSystem.WriteAllText(file ,text ,append ,encoding)

BTW, I have the files as a resource in my project & I write the files like this:
VB.NET:
Dim BooksHelpTextSch As New String(TDSDir & "\CONTENT\T3\Books\English\HelpText.sch")

Try
            If My.Settings.NoLoadTips = True Then
                My.Computer.FileSystem.WriteAllText(BooksHelpTextSch, My.Resources.HelpTextNew, False)
            Else
                My.Computer.FileSystem.WriteAllText(BooksHelpTextSch, My.Resources.HelpText, False)
            End If
        Catch ex As Exception
            MsgBox("HelpText.sch not found.")
        End Try
According to ConText the encoding of the original file is DOS(CLRF)

EDIT: I found the answer . . .
VB.NET:
My.Computer.FileSystem.WriteAllText(BooksUITextSch, My.Resources.UINoNothingLoot, False, System.Text.Encoding.Default)
 
Last edited:
Back
Top