Na continuação de uma série de postagens sobre a conversão de arquivos de texto em xml usando C #, proponho a conversão de arquivos rtf .
Parece que esse formato é bastante antigo, e muito difundido, e se não há nenhuma biblioteca para converter todos os dados em formato xml chamando um método, então definitivamente deve haver algum tipo de solução da Microsoft, pelo menos semelhante ao OpenXML . No entanto, se fosse, esse artigo não teria sido escrito.
Então, o que é um arquivo ReachTextFile (rtf) ? De um modo geral, o conteúdo do arquivo já está estruturado e até lembra uma mistura de json, xml e xpath. Isso pode ser facilmente verificado salvando algum documento do Word no formato rtf e tentando lê-lo em um editor de texto como o Notepad ++ :

Eu destaquei em vermelho uma parte do arquivo que contém informações sobre a codificação: em geral, as tags são criptografadas com a codificação ansi e o próprio texto é codificado com ansicpg1251. O texto em si é assim:

, , , , … , , , , php.
, , , , , , , . - .
, , , rtf RichTextBox
, :
- -,
Windows.Forms
, . - -, . ,
RichTextBox
, , .
, nuget RtfPipe. .
RtfPipe . rtf html. , HtmlAgilityPack.
, - ? : , , , , . , rtf- , , , , — , , , , , .
, .
public string Convert(Stream stream)
{
stream.Position = 0;
string rtf = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
rtf = sr.ReadToEnd();
}
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var html = Rtf.ToHtml(rtf);
return ClearHtml(html);
}
- string.
RtfPipe
. , - , .Net Core
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
. RtfPipe. .
.Net Framework, . var html = Rtf.ToHtml(rtf);
— html . , , , ( ), .

string ClearHtml(string html)
, xml:
string ClearHtml(string html)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var elementsWithStyleAttribute = doc.DocumentNode.SelectNodes("//@style");
var excessNodes = doc.DocumentNode.SelectNodes("//b|//u|//strong|//br");
foreach (var element in excessNodes)
{
element.ParentNode.InnerHtml = element.InnerText;
element.Remove();
}
foreach (var element in elementsWithStyleAttribute)
{
element.Attributes["style"].Remove();
}
using (StringWriter writer = new StringWriter())
{
doc.Save(writer);
html = writer.ToString();
}
StringBuilder xml = new StringBuilder();
xml.Append("<?xml version=\"1.0\"?><documents><document>");
xml.Append(html);
xml.Append("</documents></document>");
return xml.ToString();
}
- , HtmlAgilityPack nuget
doc
HtmlDocument
html
- , , . ,
style
, , , , . - C ,
StringBuilder
xml, .
, , , .
docx xlsx