How to read from and write to a .rtf or a .doc file?

I have an app that I need to read in text from a .rtf or .doc file and write to the same file.  I need it to be able to read and write bolded words and other formatting done to words.  
Right now I can get it to read and write to a .txt file but it doesn't read in or write any bolding and formatting done to words.

So intead of reading from a text file file I tried a .rtf file and a .doc file.  Reading them into my richTextBox of my app I get a bunch of garbage before the text.  

I have a button to read from the file and a button to write to the file.
Here is the code that I am currently using for this.

Case 0
                'Refresh/Read
                Dim read As String
                Dim sr As New StreamReader("c:\test.doc")
                RichTextBox1.Text = sr.ReadToEnd

                sr.Close()


            Case 1
                'Save
                Dim Write As String
                Dim sw As New StreamWriter("c:\test.doc", False)
                Write = Trim(RichTextBox1.Text)
                sw.WriteLine(Write)
                sw.Close()
jettman26Asked:
Who is Participating?
 
jrschererConnect With a Mentor Commented:
Here is a sample  (don't forger to import System.IO)  

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BOpen.Click
        OpenFileDialog1.Filter = "Rich Text (*.rtf)|*.rtf"
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                RichTextBox1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.RichText)
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub


    Private Sub BSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BSave.Click
        If File.Exists(OpenFileDialog1.FileName) Then
            Try
                RichTextBox1.SaveFile(OpenFileDialog1.FileName)
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        Else
            SaveAs()
        End If
    End Sub

    Private Sub BSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BSaveAs.Click
        SaveAs()
    End Sub

    Private Sub SaveAs()
        SaveFileDialog1.Filter = "Rich Text (*.rtf)|*.rtf"
        If SaveFileDialog1.ShowDialog = DialogResult.OK Then
            Try
                RichTextBox1.SaveFile(SaveFileDialog1.FileName)
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub
0
 
jrschererCommented:
you have to use the .SaveFile() and .LoadFile() properties.
They do the proper RTF formatting.

The .Text properties as you suggest in your code refer to a "stripped Text", whereas all RTF inherent  formatting commands are stripped.

.LoadFile and .SaveFile can only handle standard .RTF files. (some variants are supported). If you want to read or write a .Doc file you need first to convert it into .RTF with Word or another text processor.

Jack.net

0
 
jettman26Author Commented:
I am upping the point level because I need some more insight.

I got that to work.  Now i need to use an OpenFileDialog and a SaveFileDialog.
1.  When I use the OpenFileDialog to open an existing .rtf file, one that I just created on the desktop not thru my app, my Try Catch block catches it because it won't open.  It will open a .rtf file that I already Saved something to via the app before the filepath was hard coded.  How do I get this to work?

2.  This may sould dumb but how do I save to a file that was opened via my app.  I can do a Save As but how do I just Save?

3.  How do I create a new *.rtf file from my app?

Here is code that I have for the Open and SaveAs

Case 0
                    'Open
                    OpenFileDialog1.Filter = "Rich Text (*.rtf)|*.rtf"
                    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
                        Try
                            RichTextBoxPrintCtrl1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.RichText)
                        Catch
                            MsgBox("Error opening file.")
                        End Try
                    End If

Case 1
                    'SaveAs
                    'Dim Write As String
                    SaveFileDialog1.Filter = "Rich Text Files (*.rtf)|*.rtf"
                    SaveFileDialog1.ShowDialog()
                    If SaveFileDialog1.FileName <> "" Then
                        Try
                            RichTextBoxPrintCtrl1.SaveFile("SaveFileDialog1.FileName", RichTextBoxStreamType.RichText)
                        Catch
                            MsgBox("Error writing file")
                        End Try
                    End If
0
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

 
jrschererCommented:
for 1.
 Try to find out why the catch block will catch an error. Is your .rtf file not properly formatted?
just add
Catch Ex as Exception
msgbox(Ex.ToString)
End Try
The error message will give you details.

for 2.
To use Save instead Save As ou have to use the same file name from where you did load the file. You don't need to use a SaveFileDialog in this case.

for 3.
Create a RichTextBox.
Add or Append text into it
use your Case 1 code above (without the " in SaveFile()) to create the file

Jack.net
0
 
jettman26Author Commented:
Thanks for the help.  I put in the Try Catch for the open file and got this:

System.ArgumentException: Invalid file format.
at System.Windows.Forms.RichTextBox.StreamIn(Stream data, Int32 flags)
at System.Windows.Forms.RichTextBox.LoadFile(Stream data, RichTextBoxStreamType fileType)
at System.Windows.Forms.RichTextBox.LoadFile(Stream path, RichTextBoxStreamType fileType)
at WindowsApplication1.Form1.ToolBar1_ButtonClick_1(Object sender, ToolBarButtonClickEventArgs e) in C:\Documents and
Settings\bbeethe.MINDVISION\My Documents\Visual Studio Projects\TestApp1\Form1.vb:line 279

Also as far as questions 2 and 3 can you go into more detail?  I am not quite understanding them.
Thanks
0
 
jrschererCommented:
About question 1
How did you create the .rtf file you intend to load? Did you use Word or Wordpad?
0
 
jrschererCommented:
This code works fine:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "Rich Text (*.rtf)|*.rtf"
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                RichTextBox1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.RichText)
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub
0
 
jettman26Author Commented:
I just right clicked and then New then Text Document.  This creates new text document.txt.  I just changed the extension to .rtf.
That is apparently the problem because I created a file w/WordPad and also a file w/Word and they both worked fine.  Sorry for the bonehead move there.

Now on to questions 2 and 3.
0
 
jettman26Author Commented:
Thanks, this takes care of Save, Save As and Open File.  Now just need to be able to create a new file, like you can do in Word Pad.
0
 
jrschererCommented:
I am confused on this one.
The save as function creates a new file on disk, if you use it without first loading anything into RichTextBox1.
Did i misunderstand anything?
0
 
jettman26Author Commented:
You are right, I was just confused by some code.
I did find a problem.

If I launch the app and type some stuff in the RichTextBox and click the SaveAs button, it will have you enter a filename and it will create the file and save the text to it.  This part worked.  Now if I type more info into the RichTextBox, i.e. add to what was already in there, and then click the Save button, it brings up the save dialog box.  It shouldn't be doing this.
Here is my code for the Select Cases:

Case 0
                    'Open File
                    OpenFileDialog1.Filter = "Rich Text (*.rtf)|*.rtf"
                    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
                        Try
                            RichTextBoxPrintCtrl1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.RichText)
                        Catch
                            MsgBox("Error opening file.")
                        End Try
                    End If

                Case 1
                    'Save
                    If File.Exists(OpenFileDialog1.FileName) Then
                        Try
                            RichTextBoxPrintCtrl1.SaveFile(OpenFileDialog1.FileName)
                        Catch ex As Exception
                            MsgBox(ex.ToString)
                        End Try
                    Else
                        SaveAs()
                    End If

                Case 2
                    'Save As
                    SaveAs()
0
 
jettman26Author Commented:
I figured it out.

Case 1
                'Save
                If File.Exists(OpenFileDialog1.FileName) Then
                    Try
                        RichTextBoxPrintCtrl1.SaveFile(OpenFileDialog1.FileName)
                        'Displays file name in Label1
                        Dim filename As String = Path.GetFileName(OpenFileDialog1.FileName)
                        Label1.Text = filename
                    Catch ex As Exception
                        MsgBox(ex.ToString)
                    End Try
                ElseIf File.Exists(SaveFileDialog1.FileName) Then
                    Try
                        RichTextBoxPrintCtrl1.SaveFile(SaveFileDialog1.FileName)
                        'Displays file name in Label1
                        Dim filename As String = Path.GetFileName(SaveFileDialog1.FileName)
                        Label1.Text = filename
                    Catch ex As Exception
                        MsgBox(ex.ToString)
                    End Try
                Else
                    SaveAs()
                End If
0
All Courses

From novice to tech pro — start learning today.