Lars Holm Jensen's Code Blog

Just another WordPress codeblog on C#, Silverlight and all things .NET

Archive for the ‘string’ tag

C# string to alphanumeric

with one comment

Short and easy way to get the alphanumeric content of a string:

public static string ToAlphaNumeric(this string str)
{
    return new string(str.Where(c => char.IsLetterOrDigit(c)).ToArray());
}

Written by larsholm

June 16th, 2011 at 9:32 pm

Posted in .NET

Tagged with , , , ,

Persist .NET objects to XML

without comments

Here’s two extensions I use to easily persist objects to XML string in C#. Although it looks like it, it does not seem to require that the class of the object is decorated with the DataContract attribute, it just works.

public static string ToXml(this object o)
{
    StringWriter sw = new StringWriter();
    XmlWriter xw = XmlWriter.Create(sw);
    DataContractSerializer dcs = new DataContractSerializer(o.GetType());
    dcs.WriteObject(xw, o);
    xw.Close();
    return sw.ToString();
}

public static T FromXmlTo(this string s) where T : class
{
    DataContractSerializer dcs = new DataContractSerializer(typeof(T));

    StringReader sr = new StringReader(s);
    XmlReader xtr = XmlReader.Create(sr);

    return dcs.ReadObject(xtr) as T;
}

Let me here how it works out for you guys..

Written by larsholm

June 16th, 2011 at 9:06 pm

Posted in .NET

Tagged with , , , , ,