0

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?

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
DavidSNB
  • 171
  • 1
  • 10
  • 4
    Take a step back. When you write a `DateTimeOffset`, what sequence of bytes do you expect to appear? Some binary form of the `DateTimeOffset`? One of its string representations? Numbers representing the number of milliseconds past some epoch? Something else? – canton7 Feb 07 '20 at 10:58
  • 1
    It doesn't seem so. Have a look at this question: https://stackoverflow.com/questions/3377036/how-can-i-xml-serialize-a-datetimeoffset-property – Nathan 'Synaesthesia' Hitchman Feb 07 '20 at 11:01
  • Was your question answered ? If so, could you select an answer and close this question ? Thanks ! – Alexandre Nourissier Feb 08 '20 at 14:05

1 Answers1

1

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.