Visual Basic procedure to find and replace text

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hiattech
    New Member
    • May 2007
    • 6

    Visual Basic procedure to find and replace text

    This is a shot in the dark, but I'm pretty sure VB can do this. I'll give some background on the problem first.
    I work at a casino and we use embossers to print cards for players. We currently 3 different embossers that can be switched to in order to print different cards. We have a program that is run that asks a simple A, B or C to switch it. Unfortunately, we don't know who created the original file, but we figured out what it does. Basically it goes into our Oasis.ini file and searches for the line that says this:
    [Card]
    embossprinter=\ \acijpnt32\ACIJ PPRN103

    The last number can either be a 3, 4, or 5. We are attempting to move these embossers to our new print server, but to do so, we have to recreate a program that can go into the Oasis.ini file, search for the above mentioned line, and change the last part of the code. The new line would need to look something like this:
    [Card]
    embossprinter=\ \acijpnt30\ACIJ PPRN090

    the last can be 091, 092, 093, 094 or 095 (we are planning to add a few embossers in as well so we are including the range for that).
    A friend of mine looked some stuff up and said that we could set the first part as the constant that it looks for and set the last part as the variable that we can change. Unfortunately, any of the coding I've found hasn't helped at all in doing this. If anyone has some insights on this, that'd be great.

    Thanks!
  • HaggardSmurf
    New Member
    • Oct 2006
    • 12

    #2
    Just paste it all into word and press ctrl H and type what you want to find and what you want to replace it with.

    (I think thats what your asking anyways)

    Comment

    • hiattech
      New Member
      • May 2007
      • 6

      #3
      No, not quite. we know how to change the line manually, but the people we're setting this up for don't. The program will go in and change the line without them knowing. basically, they open the app, click a button with the name of the printer they want, and in the background (without them seeing anything that happens) it goes into the file, and changes the line to the correct printer. does that make more sense?

      Comment

      • Dököll
        Recognized Expert Top Contributor
        • Nov 2006
        • 2379

        #4
        Originally posted by hiattech
        No, not quite. we know how to change the line manually, but the people we're setting this up for don't. The program will go in and change the line without them knowing. basically, they open the app, click a button with the name of the printer they want, and in the background (without them seeing anything that happens) it goes into the file, and changes the line to the correct printer. does that make more sense?
        Hello, hiattech!

        Here is a link to Google results:

        http://www.google.com/search?q=Using+ a+VB+program+to +find+and+repla ce+text++in+.in i+file&rls=com. microsoft:en-us:IE-SearchBox&ie=UT F-8&oe=UTF-8&sourceid=ie7& rlz=1I7SUNA

        I have not done anything in .ini so I cannot help you there. I do have a code that replaces characters in a text file though (.txt). Let me know if it can be helpful.

        Good luck with the project!

        Comment

        • hiattech
          New Member
          • May 2007
          • 6

          #5
          well, lets see if the replacing text in a .txt works on an ini. can you give me a few lines to try? I'm semi rusty on VB, but I can change things around if need be. Basically, on button click, it has to run the changing of a line in the file.
          Thanks.

          Comment

          • Dököll
            Recognized Expert Top Contributor
            • Nov 2006
            • 2379

            #6
            Originally posted by hiattech
            well, lets see if the replacing text in a .txt works on an ini. can you give me a few lines to try? I'm semi rusty on VB, but I can change things around if need be. Basically, on button click, it has to run the changing of a line in the file.
            Thanks.
            Please stay tuned, I have to fetch for it. It goes something like:

            Code:
            Dim ReplaceThis As String
            Dim GoFetchIt As String
            Private Sub GoReplace_Click()
            GoFetchIt = Text1(0).Text
            ReplaceThis = Text1(1).Text 'Perhaps your file loaded here
            Do While InStr(LCase(GoFetchIt), ReplaceThis)
            ...something in that kind of a line
            Can't recall the rest of as of now. You'd need to tell VB to fetch the extreme right of the file though.

            In a bit!

            Comment

            • Killer42
              Recognized Expert Expert
              • Oct 2006
              • 8429

              #7
              How about this for a "quick and dirty" approach?

              [CODE=vb]Option Explicit

              Public Sub DumpFile_V02(By Val FileName As String, ByVal strChangeFrom As String, ByVal strChangeTo As String)
              Dim FileNo As Long
              Dim FileSize As Long
              Dim Buffer As String
              Dim CharNo As Long, Char As String * 1


              ' *** Step 1: Read the current file into a string variable...

              FileNo = FreeFile ' Get next available file number.
              Open FileName For Binary Access Read Write Lock Write As #FileNo
              FileSize = LOF(FileNo) ' Determine how large the file is (in bytes).
              Buffer = Space$(FileSize ) ' Set our buffer (string) to that length.
              ' The length of the string (Buffer) determines how many bytes are read...
              Get #FileNo, , Buffer ' Grab a chunk of data from the file.
              Close #FileNo

              ' *** Step 2: Make the change in memory...
              Buffer = Replace(Buffer, strChangeFrom, strChangeTo)

              ' *** Step 3: Overwrite the file...

              FileNo = FreeFile ' Get next available file number.
              Open FileName For Output Access Write Lock Write As #FileNo
              Close #FileNo

              End Sub[/CODE]Just paste this into a code module, and you've got a simple Text file string replacement routine. Just pass it the name of the INI file, the old string and the new string (for safety you should pass the full line, not just "003" or whatever).

              Note that it has none of the niceties such as error handling, and so on.

              Oh, and yes, an INI file is simply a plain ASCII text file with a different extension.

              Comment

              • Killer42
                Recognized Expert Expert
                • Oct 2006
                • 8429

                #8
                Oh rats!

                That will only work if you know the exact value that's already there.

                Hm... how about this...

                [CODE=vb]Option Explicit

                Public Sub ReplaceInFile(B yVal FileName As String, ByVal strFindThis As String, ByVal lngCharsToChang e As Long, ByVal strChangeTo As String)
                Dim FileNo As Long
                Dim Buffer As String
                Dim Length As Long
                Dim strLine As String

                Length = Len(strFindThis )
                If Length = 0 Then Exit Sub ' Drop out if o search string passed.

                ' *** Step 1: Read the current file, doing the switch as we go...

                FileNo = FreeFile ' Get next available file number.
                Open FileName For Input Access Read Lock Write As #FileNo
                Do Until EOF(FileNo)
                Line Input #FileNo, strLine
                If Left$(strLine, Length) = strFindThis Then
                strLine = Left$(strLine, Len(strLine) - lngCharsToChang e) & strChangeTo
                End If
                Buffer = Buffer & IIf((Buffer = ""), "", vbNewLine) & strLine
                Loop

                ' *** Step 2: Write back the modified file...

                FileNo = FreeFile ' Get next available file number.
                Open FileName For Output Access Write Lock Write As #FileNo
                Print #FileNo, Buffer
                Close #FileNo

                End Sub[/CODE]This is untested, so use it with care. It has the potential to totally stuff up pretty much any file you tell it to.

                The idea is that you would give it the first, constant part of the line, the number of character to replace at the end (um... I think it was 3?) and the string to replace them with.

                Comment

                • hiattech
                  New Member
                  • May 2007
                  • 6

                  #9
                  Originally posted by Killer42
                  Oh rats!

                  That will only work if you know the exact value that's already there.

                  Hm... how about this...

                  This is untested, so use it with care. It has the potential to totally stuff up pretty much any file you tell it to.

                  The idea is that you would give it the first, constant part of the line, the number of character to replace at the end (um... I think it was 3?) and the string to replace them with.
                  What version of VB is this using? I copied this in and received a lot of errors. As I went thorugh trying to find the spots I needed to replace, I found this:
                  'Line' statements are longer supported. File I/O functionality is available as 'Microsoft.Visu alBasic.FileSys tem.LineInput' and the graphics functionality is available as 'System.Drawing .Graphics.DrawL ine'.

                  I'm currently using Visual Studios 2005, but I have 2003 on my laptop. Which would be the better to use?

                  Comment

                  • hiattech
                    New Member
                    • May 2007
                    • 6

                    #10
                    Here's a screenshot of the process they go through to change the embossers. They double click a file called NewEmbosser.exe , it opens a dos-like window like below. That's what they see, and then what happens in the background that they do not see. It's simple, yet not.

                    Comment

                    • Killer42
                      Recognized Expert Expert
                      • Oct 2006
                      • 8429

                      #11
                      Sorry, this was Vb6 code. If you have a choice, I suppose it's better to use the later version (2005) unless this introduces problem in backward compatibility with your other system.

                      I'd suggest you either use 'Microsoft.Visu alBasic.FileSys tem.LineInput' as suggested by the error messages, or (probably the better option) look up how to do line by line file input in VB.Net. It probably involves using StreamReader, or FileSystemObjec t (or both).

                      I hope to soon have information about this sort of simple operation available in the Articles section, but so far we only have the Vb6 version.

                      Comment

                      • Dököll
                        Recognized Expert Top Contributor
                        • Nov 2006
                        • 2379

                        #12
                        Nuts, this was a wonderfully written code too. Are you aware of session videos for VB 2005 Express, why don't you take a listen, watch/get tips while we try to come up with something, it's sure probable to read ini through VB 2005:



                        Scroll down to watch video session.

                        Please stay tuned!

                        Comment

                        • Dököll
                          Recognized Expert Top Contributor
                          • Nov 2006
                          • 2379

                          #13
                          Originally posted by Dököll
                          Nuts, this was a wonderfully written code too. Are you aware of session videos for VB 2005 Express, why don't you take a listen, watch/get tips while we try to come up with something, it's sure probable to read ini through VB 2005:



                          Scroll down to watch video session.

                          Please stay tuned!
                          I am on a hunt for a solution for you, just started learning VB 2005, give me a month or so to come with the code. Picked up VB 2005 Cookbook by O'Reilly, looks promissing...

                          Comment

                          • danp129
                            Recognized Expert Contributor
                            • Jul 2006
                            • 323

                            #14
                            Here's a regular expression approach. I didn't build the expression to only match within any particular [section] though.

                            [CODE=vb]Option Explicit On
                            Imports System.Text.Reg ularExpressions
                            Public Class Form1

                            Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As System.EventArg s) Handles Button1.Click
                            Dim sMyIniPath As String = "c:\myini.i ni"
                            Dim sPrinterName As String = "printserver001 "
                            Dim sMyIniText As String = My.Computer.Fil eSystem.ReadAll Text(sMyIniPath )
                            sMyIniText = Regex.Replace(s MyIniText, "embossprin ter=[^\r\n]+", "embossprinter= " & sPrinterName)
                            My.Computer.Fil eSystem.WriteAl lText("c:\myini .ini", sMyIniText, False)
                            End Sub
                            End Class[/CODE]

                            Comment

                            • hiattech
                              New Member
                              • May 2007
                              • 6

                              #15
                              Hmm, i'll give that a shot. Haven't had a chance to work on this project lately so hopefully i can put a bit more into getting it done now.

                              Thanks!


                              Originally posted by danp129
                              Here's a regular expression approach. I didn't build the expression to only match within any particular [section] though.
                              .....

                              Comment

                              Working...