简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM