public static void bencode_rec(object x, MemoryStream sw)
{
if (x is int || x is long || x is ulong || x is uint)
{
byte[] op = Encoding.UTF8.GetBytes(string.Format("i{0:d}e", x));
sw.Write(op, 0, op.Length);
}
else if (x is string)
{
byte[] op = Encoding.UTF8.GetBytes(string.Format("{0:d}:{1}", ((string)x).Length, x));
sw.Write(op, 0, op.Length);
}
else if (x is byte[])
{
byte[] op = Encoding.UTF8.GetBytes(string.Format("{0:d}:", ((byte[])x).Length));
sw.Write(op, 0, op.Length);
op = (byte[])x;
sw.Write(op, 0, op.Length);
}
else if (x is ArrayList)
{
sw.WriteByte((byte)'l');
ArrayList a = (ArrayList)x;
for (int i = 0; i < a.Count; i++)
{
bencode_rec(a[i], sw);
}
sw.WriteByte((byte)'e');
}
else if (x is ListDictionary)
{
sw.WriteByte((byte)'d');
ListDictionary a = (ListDictionary)x;
ArrayList b = new ArrayList(a.Keys);
b.Sort();
foreach (string k in b)
{
bencode_rec(k, sw);
bencode_rec(a[k], sw);
}
sw.WriteByte((byte)'e');
}
else
Debug.Fail("Unknown Type");
}