views:

683

answers:

9

I am trying to load files into a windows froms (vs 2010) richTextBox but only the first line of the file is loading. I'm using:

        // Create an OpenFileDialog to request a file to open.
        OpenFileDialog openFile1 = new OpenFileDialog();

        // Initialize the OpenFileDialog to look for RTF files.
        openFile1.DefaultExt = "*.rtf";
        openFile1.Filter = "RTF Files|*.rtf";

        // Determine whether the user selected a file from the OpenFileDialog.
        if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            // Load the contents of the file into the RichTextBox.
            rtbTest.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);
        }

I've tried using rtf files created in word or word pad and have tried saving .cs files as .rtf without any success.

Any help appreciated please.

+1  A: 

I don't think the cs file is truly rtf. Try using the overload of LoadFile with a stream type such as

rtbTest.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);

Other than that, are you sure the rich text box is big enough to show more than the first line?

Edit

I tried it. I used windows forms in vs2010 (I think you are using windows forms, but not 100% sure). I created an windows forms project and saved the Project.cs as rtf. I added a button and a RichTextBox in the button's click handler I added the code from the question. It actually threw an exception when I loaded Program.rtf because it was not in the right format. I added the RichTextBoxStreamType.PlainText argument to the LoadFile call and it worked. It showed the whole file.

Mike Two
Hi Mike. Thanks, it is windows forms I'm using. I've tried this but cannot get it to work. I have plenty of space. I've tried creating .rtf files in word and word pad and saving a .cs file as rtf. Always just get the very first line.
Ted
@Ted - sorry to hear it wasn't helpful. Is your application doing this in a background thread? Or anything else that might have an impact? Have you tried what I described in the edit as a separate project just to see if it works in the bare bones case?
Mike Two
I've got it in its own project and still the same result. I've no idea. :(
Ted
+1  A: 

How did you originally save the RTF file in the first place? I agree with Mike Two, the file has got stuff in it that is not really RTF.

You might verify that the file loads properly using Wordpad, which is what I use when working with RTF files.

Update:

One investigative technique you might try is th following: after loading the file into the RichTextBox, check what the debugger gives for the RichTextBox.Rtf property - you should see all the RTF text including formatting. If it is indeed "all there" then you know you're reading the file correctly.

What worries me is that you're trying to view a code file, saved as RTF. This obviously should not be a problem, however, I recommend saving a very simple RTF file with maybe two lines of just normal text (think: lorem ipsum). If that loads ok, then you'll know it's something specific within your code file that you're reading that is screwing things up. Highly unlikely, but it's an obvious troubleshooting tactic.

As a last resort, try it on a different machine.

Charlie Salts
Hi Charlie. Thanks. I've tried what you suggested but with no luck.
Ted
It was worth a try.
Charlie Salts
+1  A: 

When all else fails, check the silly stuff... have you set the RichTextBox control be multiline? Or is it set to single line mode? Perhaps you are correctly loading the entire file, but the control is only displaying the first line because that's what you told it :)

Check RichTextBox.Multiline. It's a longshot, but maybe?

I created a sample project with a docked RichTextBox control, kept all the defaults (except Dock = DockStyle.Fill), added a simple File->Open menu and cut'n'pasted your code into the menu handler. The only change I had to make to your code was to change the second LoadFile parameter from RichTextBoxStreamType.PlainText to RichTextBoxStreamType.RichText.

A complex file (links, formatting, graphics, etc) saved from Word opened just fine for me.

Another common problem is that the control is very short. You might think it is filling your client area, but in actuality it is just a narrow strip, so you only see a single line tall. Have you set the size, docking and/or anchor properties properly? Do you see a scrollbar for your document? Is it shorter than you expect?

Simon Gillbee
For future reference, RichTextBox Controls by default are nultiline, and I'm pretty sure that you cannot make then Single-line. :)
lucifer
A: 

I think the problem is with the RichTextBoxStreamType because you set it to PlainText but you want the RichText to be loaded in the richtextbox control so why not use RichTextBoxStreamType.RichText I have tried the following code and it works properly.

        // Create an OpenFileDialog to request a file to open.
        OpenFileDialog openFile1 = new OpenFileDialog();

        // Initialize the OpenFileDialog to look for RTF files.
        openFile1.DefaultExt = "*.rtf";
        openFile1.Filter = "RTF Files|*.rtf";

        // Determine whether the user selected a file from the OpenFileDialog.
        if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            // Load the contents of the file into the RichTextBox.
            richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);
        }
Rahat Ali
+2  A: 

Okay,

It looks like the whole rtb.LoadFile() thing isn't working for yah. Could you please try loading the file this way?:

using(var of = new OpenFileDialog())
{
     of.DefaultExt="*.rtf";
     of.Filter = "RTF Files|*.rtf";

     if(of.ShowDialog() == DialogResult.OK)
          rtb.Rtf = System.IO.File.ReadAllText(of.FileName);
}

I hope this helps.

lucifer
A: 

Not sure if it is the same in WinForms as it is in WPF, but in WPF you have to use a FlowDocument set to the Document Property of the RichTextBox. this is the code I have to read from a WebStream (same thing can be done for FileStreams

protected static FlowDocument LoadRemoteRtf(string path)
    {
        var doc = new FlowDocument();
        if (!string.IsNullOrEmpty(path))
        {
            var range = new TextRange(doc.ContentStart, doc.ContentEnd);
            var downloader = new WebClient();
            Stream stream = null;
            try
            {
                stream = downloader.OpenRead(path);
                range.Load(stream, DataFormats.Rtf);
            }
            catch (Exception ex)
            {
                var props = new Dictionary<string, object> {{"URL", path}};
                Logging.WriteLogEntry("Failed to load remote RTF document.", ex, TraceEventType.Information, props);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                downloader.Dispose();
            }
        }
        return doc;
    }

MyRTB.Document = LoadRemoteRtf("http://myserver.com/docs/remote.rtf");
Nate Noonen
+1  A: 

This will work:

StreamReader sr = new StreamReader(sFileName, Encoding.Default, true); 
string sRtfFile = sr.ReadToEnd();
sr.Close();
rtbCombinedFile.Rtf = sRtfFile;

sFileName is of course the full path of the RTF file. StreamReader is part of "System.IO."

Sylverdrag
A: 

You can also try setting your RichTextBox Modifiers property to "public" and see if that works, also check that WordWrap property is set to true, that is if the file you are reading is all written on 1 line, just a long line, even if not it will still wrap those long lines based on the size of your RichTextBox.

I don't know if you use it already, have you tried ReSharper?

PumaSpeed
+1  A: 

Just read a textfile into a string and set the Rtf property of the RichTextBox.

If you're not sure if your text contains Rtf text you could use this class that I wrote. It inherits from the original RichTextBox and has a fallback if the content isn't rtf or wrong formatted.

public class RichTextBoxEx :RichTextBox
{

    public new String Rtf
    {
        get
        {
            return base.Rtf;
        }
        set
        {

            try
            {
                // is this rtf?
                if (Regex.IsMatch(value, @"^{\\rtf1"))
                {
                    base.Rtf = value;
                }
                else
                {
                    base.Text = value;
                }
            }
            catch (ArgumentException) // happens if rtf content is corrupt
            {
                base.Text = value;
            }
        }
    }

}
SchlaWiener