?
Solved

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

Posted on 2005-03-30
12
Medium Priority
?
342 Views
Last Modified: 2010-04-23
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()
0
Comment
Question by:jettman26
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
12 Comments
 
LVL 9

Expert Comment

by:jrscherer
ID: 13668943
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
 

Author Comment

by:jettman26
ID: 13674917
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
 
LVL 9

Expert Comment

by:jrscherer
ID: 13675111
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:jettman26
ID: 13675277
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
 
LVL 9

Expert Comment

by:jrscherer
ID: 13676139
About question 1
How did you create the .rtf file you intend to load? Did you use Word or Wordpad?
0
 
LVL 9

Expert Comment

by:jrscherer
ID: 13676195
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
 

Author Comment

by:jettman26
ID: 13676197
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
 
LVL 9

Accepted Solution

by:
jrscherer earned 2000 total points
ID: 13676378
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
 

Author Comment

by:jettman26
ID: 13677589
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
 
LVL 9

Expert Comment

by:jrscherer
ID: 13678020
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
 

Author Comment

by:jettman26
ID: 13678160
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
 

Author Comment

by:jettman26
ID: 13683573
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

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses
Course of the Month8 days, 16 hours left to enroll

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question