截断字符串(特定字节大小)

时间:2015-07-21 13:48:12

标签: c# .net string byte event-log

EventLog.WriteEntry方法不接受除32766/31839 字节之外的strigs ...

我想知道如何将字符串截断为特定的字节数

这是我的代码:

public static void Log(string message)
{
    const int MaxLogMessageLenght = 32766;

    string logMessage = message;
    var unicodeByteCount = 
            System.Text.ASCIIEncoding.Unicode.GetByteCount(logMessage);
    var asciiByteCount = 
            System.Text.ASCIIEncoding.ASCII.GetByteCount(logMessage);

    if (unicodeByteCount >= MaxLogMessageLenght)
    {
        // ????
        // Truncate the string to fit the WriteEntry length
        // logMessage = message.Substring(0, MaxLogMessageLenght - 5) + "...";
    }
    EventLog.WriteEntry(LogSource, logMessage, EventLogEntryType.Information);
}

1 个答案:

答案 0 :(得分:1)

你可以试试这个。

const int MaxLogMessageLength = 31839 ;

int n = Encoding.Unicode.GetByteCount(message);

if (n > MaxLogMessageLength)
{
    message = message.Substring(0, MaxLogMessageLength/2); // Most UTF16 chars are 2 bytes.

    while (Encoding.Unicode.GetByteCount(message) > MaxLogMessageLength)
        message = message.Substring(0, message.Length-1);
}

除了某些语言之外,while循环不太可能进行任何迭代。如果确实如此,它将无法提高效率。

对所需字符串长度的初始猜测是将最大长度除以2,因为大多数UTF16字符被编码为两个字节。有些可能需要两个以上的字节,在这种情况下,消息仍然太长,所以我们必须从结尾删除字符,直到它足够短。

如果这是一个问题,你可以提高效率。

相关问题