简体   繁体   中英

How to display an rtf file in WPF with Powershell?

I've been googling in vain for hours, and can't seem to find a way to view an rtf file in a powershell WPF form.

I can get the rtf file using:

$myContent = gc c:\myContent.rtf

but when I try to display it using:

$RichTextBox.appendText($myContent)

I get the encoded rtf, not the properly formatted content.

Anyone have a way to do this? Loads of examples out there about how to do this in c#, but none for PowerShell.

Thanks,

Ben

.AppendText only works with strings, not raw RTF. RTF is a sequence of control codes mixed with raw text. You need to use a different method in order to parse it:

$stream = new-object IO.MemoryStream (`
       [Text.ASCIIEncoding]::Default.GetBytes($myContent))
$RichTextBox.Selection.Load($stream, [Windows.DataFormats]::Rtf)

Hope this helps,

-Oisin

OK - so I finally got this to work with some tweaking of Oisin's post.

Will mark his as the "proper" answer, as I wouldn't have got here without him, but thought I'd post my code in case it helps anyone in future:

$myContent = gc "c:\myContent.rtf"
$ascii = (new-Object System.Text.ASCIIEncoding).getbytes($myContent)
$stream = new-Object System.IO.MemoryStream($ascii,$false)
$RichTextBox.Selection.Load($stream, [Windows.DataFormats]::Rtf) 

Cheers,

Ben

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM