Visual Basic/VB >> Find and replace text in header of binary file

by T Hayes » Wed, 25 Feb 2004 23:33:49 GMT

I have been trying to find a way to locate specific sections in the header
of a file which contains multi-frame medical image data but is wrapped in an
XML header and replace this with some different XML.

MY problem is that when I run the example below it just chugs away for ever
and nothing happens. I chose to use the common dialog to allow the doctor to
select the files easily to convert.

If the problem is with the size of the file and the content after the XML
header, maybe there is a way to limit the search to just the header.

I'm not an expert in VB6 - I mostly work with Flash but I tried to do this
one as a special favour. My code is shown below...

Thanks for any help...

Option Explicit

Private m_QuitEarly As Boolean
Public File_Name As String


Private Sub GetFiles_Click()

CDLViewer.Filter = "XIF|*.xif|Text|*.txt|All|*.*"
CDLViewer.ShowOpen
File_Name = CDLViewer.FileName

End Sub



' In the file file_name, replace occurrances of from_text
' with to_text. Return True if the string appeared and
' was replaced, False if the string was not in this file.
Private Function ReplaceInFile(ByVal File_Name As String, ByVal from_text As
String, ByVal to_text As String) As Boolean
Dim fnum As Integer
Dim file_text As String

On Error GoTo ReplaceError

' Read the file.

fnum = FreeFile
Open File_Name For Binary As fnum
file_text = Input$(LOF(fnum), #fnum)
Close #fnum

' See if the text appears.
If InStr(file_text, from_text) > 0 Then
' Replace the text.
file_text = Replace(file_text, from_text, to_text)

' Rewrite the file.
fnum = FreeFile
Open File_Name For Binary As fnum
Print #fnum, file_text;
Close #fnum

ReplaceInFile = True
End If
Exit Function

ReplaceError:
Select Case MsgBox("Error " & Err.Number & _
" processing file " & File_Name & _
vbCrLf & Err.Description & _
"Try again?", vbYesNoCancel)
Case vbYes
Resume
Case vbNo
Exit Function
Case Else
m_QuitEarly = True
Exit Function
End Select
End Function
Private Sub cmdReplace_Click()
Dim from_text As String
Dim to_text As String
Dim results As String

' Get the text to find and replace.
from_text = "TDI"
to_text = "TDI Flag"

If ReplaceInFile(File_Name, from_text, to_text) Then
results = results & " " & File_Name
End If


MsgBox results
End Sub





Visual Basic/VB >> Find and replace text in header of binary file

by Matt Williamson » Thu, 26 Feb 2004 00:54:41 GMT


From a quick glance, I'd say the problem is that you're opening the file in
binary mode and using sequential file commmands. Binary expects Put/Get of
bytes. Change your Binary's to Input for the first and Output/Append for the
second and it should work better.

HTH

Matt



an
ever
to
As





Visual Basic/VB >> Find and replace text in header of binary file

by T Hayes » Fri, 27 Feb 2004 18:06:55 GMT

i Again,

Thanks for your help. I can get it to work with simple text for replacing
(just a word or two) but the task I must perform involves rather large
multi-line chunks with an assortment of characters such as "

The following snippet is pretty typical...

<dataItem name="colorCPAMode"
type="INT"
value="0"/>
<dataItem name="colorPMIMode"
type="INT"
value="0"/>
<dataItem name="clinicalOption"
type="CHAR"
value="Cerebrovascular"/>
<dataItem name="tsiOption"
type="CHAR"
value="TDI"/>
<dataItem name="tdiFlag"
type="INT"
value="1"/>
<dataItem name="inCardiacApplication"
type="INT"
value="0"/>
<dataItem name="clinicalOptionHandle"
type="CHAR"
value="Cerebrovas"/>
<dataItem name="tsiOptionHandle"
type="CHAR"
value="CUSTOMTDI"/>
</dataGroup>
<dataGroup name="colorParameters" version="1.0" domain="INTERNAL">
<dataItem name="colorPrf"
type="INT"
value="83"/>


When I try to assign this as my from_text variable I obviously get all sorts
of errors like 'expected expression' etc. Is there a way to work with this
type of text without going through line by line and inserting CrLf and such?
I tried putting the chunks of text in text files and reading it from there
but it didn't seem to work.



Also if I want to find and replace say 3 different non-contiguous chunks
like this, should I just repeat the ReplaceInFile function with new
variables like from_text2, to_text2?



Any help much appreciated.



Terry





"Matt Williamson" < XXXX@XXXXX.COM > wrote in message
news:OQiBh$7% XXXX@XXXXX.COM ...
in
the
header
in
doctor
XML
this
from_text




Similar Threads

1. Find/Replace Header text using VBScript

2. find and replace in a binary file

I need to write a vbs to open a binary file (a pdf file) do a
find/replace then resave the file.  When I do this with the FSO
opentextfile, the resulting file is corrupt.  I have a VB program that
does it successfully by opening the file in a rtf object.  How can I
do this in vbs?

thanks,  jim

3. find and replace program for binary files ? - Visual Basic/VB

4. Find/Replace Text in Headers

The find/replace feature of VBA doesn't seem to work 
within headers & footers.  HELP.

I'm attaching my generic code below for your review.

Sub ReplaceHeadersFooters(sFind As String, sReplace As 
String)

    Dim MySelection As Variant
    Dim vntStories As Variant
    Dim x As Long
    
    With ActiveDocument

    
        For x = 0 To .StoryRanges.Count - 1
            Set MySelection = ActiveDocument.StoryRanges(1)
            
            With MySelection.Find
                .Text = sFind
                .Replacement.Text = sReplace
                .Forward = True
                .Wrap = wdFindContinue
                .Format = False
                .MatchCase = True
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute Replace:=wdReplaceAll
            End With
           
        Next x
    End With
    
    
End Sub

5. Deleting a block of text from binary file with a header - VB.Net

6. replacing text data in a binary file

I am writing a quick program to edit a binary file that contains file paths
(amongst other things). If I look at the files in notepad, they look like:

<gibberish>file//g:\pathtofile1<gibberish>file//g:\pathtofile2<gibberish>
etc.

I want to remove the "g:\" from the file paths. I wrote a console app that
successfully reads the file and writes a duplicate of it, but fails for some
reason to do the "replacing" of the "g:\". The code follows with a note
showing the line that is not working. When I look at the "s" variable in
break mode, I see that VB does not show the entire file contents, even
though when I write "s" to the second file stream, the entire original file
is duplicated. I suppose this is because the file content isn't intended to
be interpreted as a string (its binary after all). It is probably hitting
some unfriendly bytes that it can't interpret for string operations like
Replace. If that's the case, maybe I need to interact with it a character at
a time, although I'm not sure how I would do a replace that way. Any ideas
or code would be greatly appreciated. As you can tell, I don't do much
binary file I/O.

   Sub Main()
      'read the binary file into a string var
      Dim fs As New FileStream("C:\Source\Sample and
Demo\Foobar\EditFpl\Only Fools.fpl", FileMode.Open, FileAccess.Read)
      Dim sr As New StreamReader(fs, System.Text.Encoding.UTF8)
      Dim s As String = sr.ReadToEnd
      sr.Close()
      fs.Close()

      'remove the hard-coded drive letter specification
      s.Replace("file://G:\", "file://") 'THIS LINE DOES NOT WORK

      'write a new binary file with my changes
      Dim fs2 As New FileStream("C:\Source\Sample and
Demo\Foobar\EditFpl\Only Fools2.fpl", FileMode.CreateNew, FileAccess.Write)
      Dim sw As New StreamWriter(fs2, System.Text.Encoding.UTF8)
      sw.Write(s)

      sw.Close()
      fs2.Close()
   End Sub


7. replace field in primary header using find and replace in a macro - Word VBA

8. replace field in primary header using find and replace in a ma

Greg,

Thank you so much. I know you are absolutely right I have been working 
with some similar problems recently. In Steve situation, there is a great 
chance that none of the Time fields are in shapes but since your macro will 
catch any such fields, it may be safer to use that one.

By the way, you have published a lot of helpful information and macro 
solutions on your Website.


-- 
Regards
Lene Fredborg - Microsoft MVP (Word)
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word


"Greg Maxey" wrote:

>> On Aug 5, 2:14 pm, Lene Fredborg<< XXXX@XXXXX.COM >>
>> wrote:
>>>> I am not sure what "fails" means here - does the macro display an error or
>>>> does it not change any fields?
>>>>
>>>> Note that if field codes are shown when you start the macro, none of the
>>>> fields will be changed due to the code line:
>>>>
>>>>     ActiveWindow.View.ShowFieldCodes = Not ActiveWindow.View.ShowFieldCodes
>>>>
>>>> When field codes are shown, the line toggles the field codes off and TIME is
>>>> not found.
>>>>
>>>> Try to replace that line with:
>>>>
>>>>     ActiveWindow.View.ShowFieldCodes = True
>>>>
>>>> and the corresponding line at the end of the macro with:
>>>>
>>>>     ActiveWindow.View.ShowFieldCodes = False
>>>>
>>>> Does this solve the problem?
>>>>
>>>> Note: You macro will replace any occurrence of the letters imewith>
> > reatetimethis may result in undesired replacements in the document. Y>u>
> > may want to use something like the following instead it iterates though >l>
> > stories in the document and checks the fields. If a TIME field is found,>i>
> > is changed to a CREATEDATE fie>d>
> >
> > Sub ReplaceTimeFieldByCreateDateFiel>(>
> >
> >     Dim oField As Fi>l>
> >     Dim oStory As Ra>g>
> >
> >     For Each oStory In ActiveDocument.StoryRan>e>
> >         If Not oStory Is Nothing T>e>
> >             For Each oField In oStory.Fie>d>
> >                 If oField.Type = wdFieldTime T>e>
> >                     oField.Code.Text > >
> >                         Replace(oField.Code.Text, "TIME", "CREATEDAT>">
> >                 End>I>
> >             Next oFi>l>
> >         End>I>
> >     Next oSt>r>
> >
> > End >u>
> >
> >>->
> > Rega>d>
> > Lene Fredborg - Microsoft MVP (Wo>d>
> > DocTools - Denmarkwww.thedoctools.>o>
> > Document automation - add-ins, macros and templates for Microsoft W>r>
> >
> >
> >
> > "SteveB" wro>e>
>> > > OK this is my situat>o>
> >
>> > > I can record a macro and as I am recording it the process works fi>e>
>> > > I replace the field function Time with a Createdate one and it does this>i>
>> > > a Primary header's fields aswell as the main document ar>a>
> >
>> > > all the fields in question are inside primary head>r>
> >
>> > > upon re-running the macro it fai>s>
> >
>> > > regardless of where I place the cursor prior to running the mac>o>
> >
>> > > please help me - I am in danger of  becoming insane over thi> >
> >
>> > > This is the ma>r>
> >
>> > > Sub Replace>(>
>> > > >
>> > > ' Replacer Ma>r>
>> > > ' Macro recorded 05/08/2008 by Si>u>
>> > > >
>> > >     ActiveWindow.View.ShowFieldCodes = Not ActiveWindow.View.ShowFieldCo>e>
>> > >     Selection.Find.ClearFormatt>n>
>> > >     Selection.Find.Replacement.ClearFormatt>n>
>> > >     With Selection.F>n>
>> > >         .Text = "TI>E>
>> > >         .Replacement.Text = "CREATEDA>E>
>> > >         .Forward = T>u>
>> > >         .Wrap = wdFindConti>u>
>> > >         .Format = Fa>s>
>> > >         .MatchCase = Fa>s>
>> > >         .MatchWholeWord = Fa>s>
>> > >         .MatchWildcards = Fa>s>
>> > >         .MatchSoundsLike = Fa>s>
>> > >         .MatchAllWordForms = Fa>s>
>> > >     End W>t>
>> > >     Selection.Find.Execute Replace:=wdReplace>l>
>> > >     ActiveWindow.View.ShowFieldCodes = Not ActiveWindow.View.ShowFieldCo>e>
>> > > End >u>
> >
>> > > Thanks in advance for any hel> >
> >
>> > > Steve- Hide quoted tex> >
> >
> > - Show quoted tex> -
>> 
> Le>e,
>> 
> I am sure that your code would be perfectly suitable 99.99% of >he
> time, but it will miss TIME fields that are contained in the TextRa>ge
> of shapes located in headers or footers.  This is something tha> I
> discovered when I was working on my VBA Find and Replace AddIn that>is
> posted on my website.   To get them all you would need to process e>ch
> shape in the shaperange using something like th>s:
>> 
> Sub ScratchMacr>()
> Dim rngstory As Word.Ra>ge
> Dim oFld As Word.Fi>ld
> Dim oShp As Word.Sh>pe
> Dim i As L>ng
> 'Handle unlinked secti>ns
> i = ActiveDocument.Sections(1).Headers(1).Range.StoryT>pe
> With ActiveDocum>nt
>   For Each rngstory In .StoryRan>es
>     'Iterate through all linked stor>es
>    >Do
>       For Each oFld In rngstory.Fie>ds
>         With o>ld
>           If .Type = wdFieldTime T>en
>              .Code.Text = Replace(oFld.Code.Text, "TIM>",
> "CREATEDAT>")
>           End>If
>           .Upd>te
>         End W>th
>       Next o>ld
>       On Error Resume N>xt
>       Select Case rngstory.StoryT>pe
>         Case 6, 7, 8, 9, 10,>11
>           'Interate through all shapes in header/foot>rs
>           If rngstory.ShapeRange.C>unt > 0 T>en
>             For Each oShp In rngstory.ShapeRa>ge
>               If oShp.TextFrame.HasText T>en
>                 For Each oFld In oShp.TextFrame.TextRange.Fie>ds
>                   With o>ld
>                   If oFld.Type = wdFieldTime T>en
>                     oFld.Code.Text > _
>                         Replace(oFld.Code.Text, "TIME", "CREATEDAT>")
>                    End>If
>                    .Upd>te
>                   End W>th
>                 Next o>ld
>               End>If
>             Next o>hp
>           End>If
>         Case E>se
>           'Do Noth>ng
>       End Sel>ct
>       On Error GoT> 0
>       'Get next linked story (if a>y)
>       Set rngstory = rngstory.NextStoryRa>ge
>     Loop Until rngstory Is Noth>ng
>   Next rngst>ry
> End W>th
> End >ub
>> 
> Thought you would like to kn>w.
>