Wednesday, 23 December 2009

Misc stream / string / serialization helpers

Some useful stream / string / serialization helpers

public string GetStringFromStream(Stream str)
{
    string s = null;

    using (StreamReader sr = new StreamReader(str))
    {
        s = sr.ReadToEnd();
    }

    return s;
}

public Stream GetStreamFromString(string s, out string charset)
{
    Stream str = null;
    charset = string.Empty;

    // Write the data to a new stream...
    using (StreamWriter sw = new StreamWriter(new MemoryStream()))
    {
        sw.Write(s);
        sw.Flush();
        sw.BaseStream.Seek(0, SeekOrigin.Begin);
        charset = sw.Encoding.HeaderName;
        str = sw.BaseStream;
    }
    return str;
}

public Stream GetStreamFromObject(object instance)
{
    Stream str = new MemoryStream();
    XmlSerializer xmlz = new XmlSerializer(instance.GetType());
    xmlz.Serialize(str, instance);

    return str;
}

public string SerializeInstance(object instance, Type t)
{
    MemoryStream ms = new System.IO.MemoryStream();
    XmlSerializer xmlz = new XmlSerializer(t);
    xmlz.Serialize(ms, instance);
    ms.Seek(0, SeekOrigin.Begin);

    using (StreamReader sr = new StreamReader(ms))
    {
        return sr.ReadToEnd();
    }
}

public static T DeserializeInstance(string xml)
{
    XmlSerializer xmlz = new XmlSerializer(typeof(T));
    return (T)xmlz.Deserialize(new XmlTextReader(new StringReader(xml)));
}

public static T DeserializeInstance(System.IO.Stream str)
{
    XmlSerializer xmlz = new XmlSerializer(typeof(T));
    return (T)xmlz.Deserialize(str);
}

No comments: