views:

77

answers:

2

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

+2  A: 

.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

x0n
Think I'm getting warmer, but get this error when I try to create the MemoryStream - New-Object : Cannot find an overload for "MemoryStream" and the argument count: "123".
Ben
+1  A: 

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

Ben
sorry,yeah, I probably broke it by trying to format it better to read. The backtick "`" is a line continuation character, like VB's underscore "_"
x0n