如何确定C#中的文本格式 [英] How to determine text format in C#

查看:157
本文介绍了如何确定C#中的文本格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以确定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 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#中的文本格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆