C# · 12月 29, 2021

c# – 使用格式化将富文本数据的数据存储到数据库

我在wpf中是新的,我想将富文本框的数据及其格式(斜体,彩色,粗体)存储到数据库(MysqL)中.
当我保存数据时,格式化被忽略.
此外,当我从数据库加载到富文本框时,它会显示同一行中的所有文本.
期待您的帮助和建议! public void save() { MysqLConnection conn = new MysqLConnection(connString); MysqLCommand command = conn.CreateCommand(); string richText = new TextRange(rt1.Document.ContentStart,rt1.Document.ContentEnd).Text; string s = WebUtility.HtmlEncode(richText); command.Parameters.AddWithValue(“@s”,s); command.CommandText = “insert into proc_tra (procedures) values (@s)”; conn.open(); command.ExecuteNonQuery(); conn.Close(); }public void load() { MysqLConnection conn = new MysqLConnection(connString); MysqLCommand command = conn.CreateCommand(); command.CommandText = “select * from proc_tra where id_pt=4″; rt1.Document.Blocks.Clear(); conn.open(); MysqLDataReader dr; dr = command.ExecuteReader(); string k=””; while (dr.Read()) { k += dr[“procedures”].ToString(); } var p = new Paragraph(); var run = new Run(); run.Text = WebUtility.HtmlDecode(k); p.Inlines.Add(run); rt1.Document.Blocks.Add(p); }解决方法 要获取将保存在数据库中的格式化文本: string rtfText; //string to save to dbTextRange tr = new TextRange(richText@R_228_2419@.Document.ContentStart,richText@R_228_2419@.Document.ContentEnd);using (MemoryStream ms = new MemoryStream()){ tr.Save(ms,DataFormats.Rtf); rtfText = Encoding.ASCII.GetString(ms.ToArray());}

要还原从数据库检索的格式化文本:

string rtfText= … //string from dbbyte[] byteArray = Encoding.ASCII.GetBytes(rtfText);using (MemoryStream ms = new MemoryStream(byteArray)){ TextRange tr = new TextRange(richText@R_228_2419@.Document.ContentStart,richText@R_228_2419@.Document.ContentEnd); tr.Load(ms,DataFormats.Rtf);}

您也可以使用XAML格式,使用DataFormats.XAML加载保存.