将字符串[,]转换为字节,以便通过c#.net中的socket发送

时间:2012-10-01 16:41:56

标签: c#-3.0

  

可能重复:
  How to convert an int[,] to byte[] in C#

我想通过套接字发送一个二维字符串数组(string [n,m]),它必须转换为字节数组。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以使用前8个字节来存储数组的维度:

public static byte[] ToByteArray(string[,] input)
{
    using (var stream = new MemoryStream())
    using (var writer = new BinaryWriter(stream, Encoding.UTF8))
    {
        var rows = input.GetLength(0);
        var cols = input.GetLength(1);
        writer.Write(rows);
        writer.Write(cols);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                writer.Write(input[i, j]);
            }
        }
        return stream.ToArray();
    }
}

并将字节数组转换回2D字符串数组:

public static string[,] FromByteArray(byte[] input)
{
    using (var stream = new MemoryStream(input))
    using (var reader = new BinaryReader(stream, Encoding.UTF8))
    {
        var rows = reader.ReadInt32();
        var cols = reader.ReadInt32();
        var result = new string[rows, cols];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                result[i, j] = reader.ReadString();
            }
        }
        return result;
    }
}