选择.rtf中页眉和页脚之间的内容

问题描述 投票:0回答:1

如何仅获取 .rtf 文件的内容?
如何在 C# 中找到 .rtf 文件的页眉停止位置和页脚开始位置?

我读过

using (var sr = new StreamReader(myRtfFilePath))
{
    fullText = sr.ReadToEnd();
    encoding = sr.CurrentEncoding;
}

我可以这样找到我写的内容

var startIndex = fullText.IndexOf("start");

但这意味着我必须手动将“开始”和“结束”添加到我的 .rtf 文件中,以便我可以看到内容的开始位置和结束位置。

c# ms-word rtf
1个回答
0
投票

要在 C# 中仅提取 RTF 文件的内容,可以使用 System.Windows.Forms.RichTextBox 控件,该控件具有处理 RTF 格式的内置功能。以下是您可以如何执行此操作的示例:

using System.Windows.Forms;

class RtfExtractor
{
    public string ExtractRtfContent(string rtfFilePath)
    {
        string content = "";

        // Create a RichTextBox control
        using (RichTextBox richTextBox = new RichTextBox())
        {
            // Load the RTF file into the RichTextBox
            richTextBox.LoadFile(rtfFilePath, RichTextBoxStreamType.RichText);

            // Extract the plain text content
            content = richTextBox.Text;
        }

        return content;
    }
}

关于您的第二个问题,即查找 RTF 文件的页眉停止位置和页脚开始位置。

如果您在 RTF 文件中手动添加了“开始”和“结束”等标记,则可以使用您提到的 IndexOf 查找这些标记之间的内容。这是一个例子:

class RtfMarkerFinder
{
    public string ExtractContentBetweenMarkers(string rtfFilePath, string startMarker, string endMarker)
    {
        string fullText = "";

        // Read the entire RTF file into a string
        using (var sr = new StreamReader(rtfFilePath))
        {
            fullText = sr.ReadToEnd();
        }

        // Find the index of the start marker
        int startIndex = fullText.IndexOf(startMarker);
        if (startIndex == -1)
        {
            // Start marker not found
            return "";
        }

        // Find the index of the end marker after the start marker
        int endIndex = fullText.IndexOf(endMarker, startIndex + startMarker.Length);
        if (endIndex == -1)
        {
            // End marker not found after the start marker
            return "";
        }

        // Extract the content between the markers
        int contentStart = startIndex + startMarker.Length;
        int contentLength = endIndex - contentStart;
        string extractedContent = fullText.Substring(contentStart, contentLength);

        return extractedContent;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.