如何在带有 Windows.Storage 的 UWP 中使用 System.IO Serializers [英] How to use System.IO Serializers in UWP with Windows.Storage

查看:30
本文介绍了如何在带有 Windows.Storage 的 UWP 中使用 System.IO Serializers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够拥有一个类对象列表(List),并且能够轻松地写入和读取文本文件.

I want to be able to have a list of class objects (List<Class>) and be able to easily write and read to a text file.

在我以前使用的旧控制台应用程序Windows Forms应用程序中:

In my older Console Applications and Windows Forms applications I used to use:

List<Class> _myList = ... 
WriteToFile<List<Class>>("C:\\...\\Test.txt", Class _myList)

public static void WriteToFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
        {
            TextWriter writer = null;
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                writer = new StreamWriter(filePath, append);
                serializer.Serialize(writer, objectToWrite);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

但是,这在 UWP 应用程序 中不起作用,我必须使用 StorageFolderStorageFile,它们可以很好地将简单文本写入像这样的文件:

However this does not work in a UWP application and I have to use StorageFolder and StorageFile which works fine for writing simple text to a file like this:

StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file= await storageFolder.GetFileAsync("Test.txt");
await FileIO.WriteTextAsync(sampleFile, "Example Write Text");

但我希望能够使用 XmlSerializerStreamWriter 的更高级功能将类列表写入我的 UWP 应用程序中的文件.

But I want to be able to use the more advanced functionality of XmlSerializer along with StreamWriter to write lists of classes to a file within my UWP application.

我该怎么做?

推荐答案

你可以使用基于 Stream 的版本你使用的方法,例如 StreamWriter 有一个构造函数它需要一个 System.IO.Stream 实例.

You can use the Stream-based versions the methods you use, for example StreamWriter has a constructor which takes a System.IO.Stream instance.

要从 StorageFile 获取 System.IO.Stream,您可以使用 OpenStreamForWriteAsyncOpenStreamForReadAsync 扩展方法,位于 UWP 的 System.IO 命名空间中:

To get a System.IO.Stream from a StorageFile, you can use the OpenStreamForWriteAsync and OpenStreamForReadAsync extension methods, which are in the System.IO namespace on UWP:

//add to the top of the file
using System.IO;

//in your code
var stream = await myStorageFile.OpenStreamForWriteAsync();
//do something, e.g.
var streamWriter = new StreamWriter(stream);

这篇关于如何在带有 Windows.Storage 的 UWP 中使用 System.IO Serializers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆