如何在带有 Windows.Storage 的 UWP 中使用 System.IO Serializers

编程入门 行业动态 更新时间:2024-10-24 21:36:23
本文介绍了如何在带有 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 应用程序 中不起作用,我必须使用 StorageFolder 和 StorageFile,它们可以很好地将简单文本写入像这样的文件:

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");

但我希望能够使用 XmlSerializer 和 StreamWriter 的更高级功能将类列表写入我的 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,您可以使用 OpenStreamForWriteAsync 和 OpenStreamForReadAsync 扩展方法,位于 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

本文发布于:2023-11-09 22:55:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Storage   Windows   UWP   IO

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!