您如何将多字符串与C#字符串集合相互转换? [英] How do you convert multistring to/from C# string collection?

查看:55
本文介绍了您如何将多字符串与C#字符串集合相互转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows API中,多字符串(以null终止的双精度字符串,以null分隔的字符串)是常见的.将从API返回的多字符串转换为C#字符串集合,反之亦然的一种好方法是什么?

Multistrings (double null-terminated string of null-separated strings) are common in the Windows API. What's a good method for converting a multistring returned from an API to a C# string collection and vice versa?

我对正确处理字符编码(Windows XP及更高版本)特别感兴趣.

I'm especially interested in proper handling of character encoding (Windows XP an later).

以下方法似乎可以创建多字符串,但是我没有解码多字符串的示例.

The following method seems to be okay for creating a multistring, but I don't have an example of decoding a multistring.

static string StringArrayToMultiString(
    ICollection<string> stringArray
    )
{
    StringBuilder multiString = new StringBuilder();


    if (stringArray != null)
    {
        foreach (string s in stringArray)
        {
            multiString.Append(s);
            multiString.Append('\0');
        }
    }

    return multiString.ToString();
}

推荐答案

这可能很幼稚,但是如何做:

This might be naïve, but how about:

static string[] MultiStringToArray(string multiString)
{
    return multiString.TrimEnd('\0').Split('\0');
}

<罢工>另外-您不是在 StringArrayToMultiString 中丢失了最后的 \ 0 (您声明为双空终止)吗?如果数组是一个 params string [] 数组-类似于:

Also - aren't you missing the final \0 (you state double-null-terminated) in StringArrayToMultiString? And it might be easier to call if the array was a params string[] array - something like:

    static string StringArrayToMultiString(params string[] values)
{
    if (values == null) throw new ArgumentNullException("values");
    StringBuilder multiString = new StringBuilder();

    foreach (string s in values)
    {
        multiString.Append(s);
        multiString.Append('\0');
    }
    return multiString.ToString();
}

[在澄清有关最终\ 0之后进行了编辑]

[edited after clarification about final \0]

这篇关于您如何将多字符串与C#字符串集合相互转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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