DavidSNB
DavidSNB

Reputation: 181

How to Write DateTimeOffset to file useing StreamWriter

I use this function for writing to file in my UWP project:

public static async Task WriteToFileAsync<T>(string fileName, T objectToWrite) where T : new()
{
    StorageFolder storageFolder = ApplicationData.Current.LocalFolder
    TextWriter writer = null;
    try
    {
        StorageFile file = await storageFolder.CreateFileAsync(fileName + ".txt");
        var serializer = new XmlSerializer(typeof(T));
        var stream = await file.OpenStreamForWriteAsync();
        writer = new StreamWriter(stream);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

However this doesn't seem to write DateTimeOffset values to file.

The solution that I currently use is converting it to a string but this seems a bit messy.

Is there a more elegant way to do this?

Upvotes: 0

Views: 95

Answers (1)

Alexandre Nourissier
Alexandre Nourissier

Reputation: 338

Ultimately, even if DateTimeOffset is a Structure, it more common and useful expression in a file is as a string. You can choose the format of your liking. If you want to be clean, you can use the ISO 8601 format, which supports time offsets.

Upvotes: 1

Related Questions