思路:
richtextbox不能直接识别doc文件,但是我们可以通过使用引用word,先把doc转换成临时Rtf文件,从而实现
需要添加引用
Microsoft.Office.Interop.Word.Application |
If InStr(ReadFile, ".doc") > 0 Then ' 读取doc文件
Try
Dim wordobj As New Word.Application
Dim tmpFilePath As String = Application.StartupPath + "tmp.rtf"
With wordobj
'关闭显示打开文件
.Visible = False
.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
'读取文件
.Documents.Open(ReadFile)
'原有直接替换方法,无法保留格式
'RichTextBox1.Text = Replace(.ActiveDocument.Content.Text, Chr(13), vbCrLf)
'我的方法,保存为RTF格式临时文件
.ActiveDocument.SaveAs(tmpFilePath, Word.WdSaveFormat.wdFormatRTF)
.ActiveWindow.Close()
End With
wordobj = Nothing
RichTextBox1.LoadFile(tmpFilePath)
Catch ex As Exception
MsgBox("请确认是否正常安装了word软件?", vbCritical, "提示")
End Try
ElseIf InStr(ReadFile, ".rtf") > 0 Then
'RTf格式直接读取
RichTextBox1.LoadFile(ReadFile)
Else
'TXT格式,需要定义读取方式
RichTextBox1.LoadFile(ReadFile, RichTextBoxStreamType.PlainText)
End If