问题描述
有没有一种方法可以确定C#/。NET中的文本格式?这样的东西会非常有用。
public TextFormat TextTools.GetTextFormat(string text);
$ b $ switch(TextTools.GetTextFormat(mystring))
{
case TextFormat.RichText:break;
case TextFormat.PlainText:break;
$ / code $ / pre
$ b $我看了一下周围的msdn,但没有找到这样的工具解决方案这是一个很好的启发式检查,但是您可以尝试从类似这样的事情开始构建自己的函数(当然,您可以扩展它(text.TrimStart()方法来处理不同的格式):
$ b $ pre $ if(text.TrimStart .StartsWith({\rtf1,StringComparison.Ordinal))
return TextFormat.RichText;
返回TextFormat.PlainText;
$ b 更好的检查意味着你解析RTF文本以确保它不仅仅是一个字符串,似乎RTF。因为解析可能是非常广泛的(就时间而言),那么我建议首先做一个快速检查,以排除所有肯定不是RTF的:
公共静态的TextFormat的getFormat(文本串){
如果(text.TrimStart()。StartsWith( {\rtf1,StringComparison.Ordinal)){
如果(IsValidRtf(文本))
返回TextFormat.RichText;
}
return TextFormat.PlainText;
$ / code>
在最嵌套的 if $ c $你可以决定如何处理看似RTF的文本,但是这个文本是无效的(在这个例子中,我只是把它看作纯文本)。一个可能的,天真低效的实现 IsValidRtf()
依赖于 RichTextBox
控制实现(然后是Windows API实现)可能是:
pre code $ private static bool IsValidRtf(string text){
try {
new RichTextBox ().Rtf = text;
}
catch(ArgumentException){
return false;
}
return true;
}
Is there a way to determine the format of text in C#/.NET
something like this would be very useful.
public TextFormat TextTools.GetTextFormat(string text);
switch(TextTools.GetTextFormat(mystring))
{
case TextFormat.RichText: break;
case TextFormat.PlainText: break;
}
Ive looked around on msdn but couldnt find such a tool
It's a pretty heuristic check but you can try to build your own function starting with something like this (of course you can extend it to handle different formats):
public static TextFormat GetFormat(string text) {
if (text.TrimStart().StartsWith("{\rtf1", StringComparison.Ordinal))
return TextFormat.RichText;
return TextFormat.PlainText;
}
A better check implies you parse RTF text to be sure it's not just a random string that seems RTF. Because parsing may be expansive (in terms of time) then I'd suggest to first do a quick check to exclude everything for sure isn't RTF:
public static TextFormat GetFormat(string text) {
if (text.TrimStart().StartsWith("{\rtf1", StringComparison.Ordinal)) {
if (IsValidRtf(text))
return TextFormat.RichText;
}
return TextFormat.PlainText;
}
In the most nested if
you can decide what to do with text that seems RTF but it's not valid (in this example I just consider it as plain text). A possible, naive and inefficient, implementation of IsValidRtf()
that relies on RichTextBox
control implementation (then down to Windows API implementation) may be:
private static bool IsValidRtf(string text) {
try {
new RichTextBox().Rtf = text;
}
catch (ArgumentException) {
return false;
}
return true;
}
这篇关于如何确定C#中的文本格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!