简体   繁体   English

如何使用 StreamWriter 将 DateTimeOffset 写入文件

[英]How to Write DateTimeOffset to file useing StreamWriter

I use this function for writing to file in my UWP project:我使用此函数在我的 UWP 项目中写入文件:

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.但是,这似乎没有将DateTimeOffset值写入文件。

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.最终,即使 DateTimeOffset 是一个结构,它在文件中更常见和有用的表达式是作为字符串。 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.如果你想要干净,你可以使用支持时间偏移的 ISO 8601 格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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