将 RTF 文件加载到 Windows RichTextBox 中的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2750282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:23:33  来源:igfitidea点击:

Problem loading RTF file into windows richTextBox

c#windowsrichtextbox

提问by Ted

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:

我正在尝试将文件加载到 windows froms (vs 2010) richTextBox 中,但只有文件的第一行正在加载。我正在使用:

        // 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.

我尝试使用在 word 或 word pad 中创建的 rtf 文件,并尝试将 .cs 文件保存为 .rtf 没有任何成功。

Any help appreciated please.

请感谢任何帮助。

回答by Ted

Okay,

好的,

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

看起来整个 rtb.LoadFile() 东西对你不起作用。您可以尝试以这种方式加载文件吗?:

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.

我希望这有帮助。

回答by Sylverdrag

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."

sFileName当然是RTF文件的完整路径。StreamReader 是“System.IO”的一部分。

回答by Mike Two

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

我不认为 cs 文件是真正的 rtf。尝试使用LoadFile流类型的重载,例如

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 RichTextBoxin 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.PlainTextargument to the LoadFilecall and it worked. It showed the whole file.

我尝试过这个。我在 vs2010 中使用了 windows 窗体(我认为你正在使用 windows 窗体,但不是 100% 确定)。我创建了一个 windows 窗体项目并将 Project.cs 保存为 rtf。我RichTextBox在按钮的单击处理程序中添加了一个按钮和一个,我添加了问题中的代码。当我加载 Program.rtf 时,它实际上抛出了一个异常,因为它的格式不正确。我RichTextBoxStreamType.PlainTextLoadFile调用中添加了参数并且它起作用了。它显示了整个文件。

回答by Charlie Salts

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.

您最初是如何保存 RTF 文件的?我同意 Mike Two 的观点,该文件中包含的内容并非真正的 RTF。

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

您可以使用写字板验证文件是否正确加载,这是我在处理 RTF 文件时使用的方法。

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.Rtfproperty - you should see all the RTF text including formatting. If it is indeed "all there" then you know you're reading the file correctly.

您可能尝试的一种调查技术如下:将文件加载到 RichTextBox 后,检查调试器为该RichTextBox.Rtf属性提供的内容 - 您应该看到所有 RTF 文本,包括格式。如果它确实“全部都在那里”,那么您就知道您正在正确读取文件。

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 verysimple RTF file with maybe two lines of just normal text (think: lorem ipsum). If thatloads 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.

我担心的是,您正在尝试查看保存为 RTF 的代码文件。这显然不应该是一个问题,但是,我建议保存一个非常简单的 RTF 文件,其中可能只有两行普通文本(想想:lorem ipsum)。如果加载好了,你就知道你的代码文件中它的具体的东西,你正在阅读的是拧的事情了。极不可能,但这是一个明显的故障排除策略。

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

作为最后的手段,请在不同的机器上尝试。

回答by Simon Gillbee

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 :)

当所有其他方法都失败时,检查一些愚蠢的东西...您是否将 RichTextBox 控件设置为多行?还是设置为单行模式?也许您正确加载了整个文件,但控件只显示第一行,因为那是您告诉它的:)

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

检查RichTextBox.Multiline。这是一个远景,但也许?

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 LoadFileparameter from RichTextBoxStreamType.PlainTextto RichTextBoxStreamType.RichText.

我创建了一个带有停靠的 RichTextBox 控件的示例项目,保留了所有默认值(除了Dock = DockStyle.Fill),添加了一个简单的 File->Open 菜单并将您的代码剪切和粘贴到菜单处理程序中。我必须对您的代码进行的唯一更改是将第二个LoadFile参数从更改RichTextBoxStreamType.PlainTextRichTextBoxStreamType.RichText

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

从 Word 保存的复杂文件(链接、格式、图形等)对我来说打开得很好。

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?

另一个常见的问题是控件很短。您可能认为它正在填充您的客户区,但实际上它只是一个窄带,因此您只能看到一行高。您是否正确设置了大小、停靠和/或锚点属性?您是否看到文档的滚动条?它比您预期的要短吗?

回答by Jürgen Steinblock

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

只需将文本文件读入字符串并设置 RichTextBox 的 Rtf 属性即可。

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.

如果您不确定您的文本是否包含 Rtf 文本,您可以使用我编写的这个类。它继承自原始 RichTextBox,如果内容不是 rtf 或格式错误,则有一个后备。

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;
            }
        }
    }

}

回答by Sheikh Rahat Ali

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.

我认为问题出在 RichTextBoxStreamType 上,因为您将其设置为 PlainText 但您希望 RichText 加载到 Richtextbox 控件中,所以为什么不使用 RichTextBoxStreamType.RichText 我已经尝试了以下代码并且它可以正常工作。

        // 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);
        }

回答by PumaSpeed

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.

您还可以尝试将 RichTextBox Modifiers 属性设置为“public”并查看是否有效,同时检查 WordWrap 属性是否设置为 true,即如果您正在阅读的文件全部写在 1 行上,即使是很长的一行,如果不是,它仍然会根据 RichTextBox 的大小包装那些长行。

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

不知道大家有没有用过,有没有试过ReSharper?

回答by Nate Noonen

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

不确定它在 WinForms 中是否与在 WPF 中相同,但在 WPF 中,您必须使用设置为 RichTextBox 的文档属性的 FlowDocument。这是我必须从 WebStream 中读取的代码(可以对 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");