Wednesday, October 3, 2018

Simple way to read and write files asynchronously in C#

Two simple ways to read and write files in C#.

async Task<string> ReadFromFileAsync(string filePath)
{
    using (TextReader file = File.OpenText(filePath))
    {
        return await file.ReadLineAsync();
    }
}

async Task WriteToFileAsync(string filePath, string text)
{
    using (TextWriter tw = File.CreateText(filePath))
    {
        await tw.WriteAsync(text);
    }
}

XML Serialization and Deserialization

Often we need to serialize and deserialize object back and forth to XML in application development with C#. Below are two generic method which are quite handy for such.

Serialize an object to XML string. 

string Object2Xml<T>(T obj)
{
    var sw = new StringWriter();
    var serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(sw, obj);
    return sw.ToString();
    
}

Deserialize and XML string  back to object.

T Xml2Object<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(new StringReader(xml));
}