Load an RTF file from resources to a RichTextBox in a WPF application
Asked Answered
C

2

6

I am trying to load the content of an RTF file, which I have put inside resources (through Project->Properties->Resources->Add File).

I want to load Agreement.rtf's content to a RichTextBox and I have tried the following:

Dim stream As Stream
stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(My.Resources.ResourceManager.GetObject("Agreement").GetType(), "IOpzioni.Agreement.rtf")
RichTextBox1.SelectAll()

RichTextBox1.Selection.Load(stream, DataFormats.Rtf)

also

   stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(My.Resources.Agreement.GetType(), "IOpzioni.Agreement.rtf")

IOpzioni is my default namespace (I have double checked that).

Nothing seems to work. What is the correct way to do this?

Cirrate answered 20/12, 2011 at 12:56 Comment(0)
A
7

I achieved this in a somewhat simple way in my WPF application. See my blog here: http://devdare.blogspot.com/2014/03/wpf-loading-rtf-document-in-richtextbox.html

  1. In your WPF projects, add a Resources.resx file (if it's not already there)
  2. Add your RTFDoc.rtf in your Resources.resx file
  3. Along with your Resources.resx file, there would be code behind file: Resources.Designer.cs. Open it and copy its namespace and class name. In my case it is Surf.Resources.Resource1

I used this to load the RTF resource in my WPF RichTextBox control. Here are the lines from the code behind:

using Surf.Resources;

void Surface_Loaded(object sender, RoutedEventArgs e)
{             
    var stream = new MemoryStream(Encoding.Unicode.GetBytes(Resource1.RTFDoc));
    RichTextBox1.Selection.Load(stream, DataFormats.Rtf);
}

Surf is my project name here. Hope this helps.

Arnie answered 24/3, 2014 at 11:14 Comment(0)
U
0

The first thing is to ensure the file is an embedded resource of the project. Then ensure the resource name of the file is the folder location, dot separated starting at the root of the project. For example, let's say I have project Test where the resources folder is under Runtime\Source, then I should set the name as Test.Runtime.Source.Resources.Agreement.rtf.

Then just call this method (it's in C# but you can convert it), send your name, in this example "Test.Runtime.Source.Resources.Agreement.rtf" to read the contents:

  public static string GetResourceByName(string resource)
  {
     Assembly assembly = Assembly.GetExecutingAssembly();
     StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resource));
     return reader.ReadToEnd();
  }
Undercool answered 20/12, 2011 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.