如何在 Windows 8 中使用 StreamWriter 写入文件?

How write a file using StreamWriter in Windows 8?(如何在 Windows 8 中使用 StreamWriter 写入文件?)

本文介绍了如何在 Windows 8 中使用 StreamWriter 写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 windows-8 中创建 StreamWriter 对象时遇到问题,通常我只是创建一个实例,只是将字符串作为参数传递,但在 Windows 8 中,我收到一个错误,表明它应该收到一个 Stream,但我注意到 Stream 是一个抽象类,有人知道编写 xml 文件的代码是什么吗?顺便说一句,我使用 .xml 是因为我想保存序列化对象,或者有人知道吗知道如何在 Windows 8 中将序列化对象保存到文件中吗?

I'm having trouble when creating a StreamWriter object in windows-8, usually I just create an instance just passing a string as a parameter, but in Windows 8 I get an error that indicates that it should recieve a Stream, but I noticed that Stream is an abstract class, Does anybody knows how will be the code to write an xml file?, BTW I'm using .xml because I want to save the serialized object, or does anyone knows how to save to a file a serialized object in Windows 8?.

有什么想法吗?

当前使用的是 Windows 8 Consumer Preview

Currently using Windows 8 Consumer Preview

代码:

StreamWriter sw = new StreamWriter("person.xml");

错误:

'System.IO.StreamWriter.StreamWriter(System.IO.Stream)'的最佳重载方法匹配有一些无效参数

推荐答案

你可以使用类似这样的东西来代替 StreamWriter:

Instead of StreamWriter you would use something like this:

StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync();

using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
    {
        using (DataWriter dataWriter = new DataWriter(outputStream))
        {
            //TODO: Replace "Bytes" with the type you want to write.
            dataWriter.WriteBytes(bytes);
            await dataWriter.StoreAsync();
            dataWriter.DetachStream();
        }

        await outputStream.FlushAsync();
    }
}

您可以查看 StringIOExtensions 类/winrtxamltoolkit.codeplex.com/">WinRTXamlToolkit 库供示例使用.

You can look at the StringIOExtensions class in the WinRTXamlToolkit library for sample use.

编辑*

虽然以上所有内容都应该有效 - 它们是在 FileIO 类在 WinRT 中可用,这简化了上述解决方案解决的大多数常见场景,因为您现在只需调用 await FileIO.WriteTextAsync(file, contents) 将文本写入文件,还有读取、写入或附加字符串、字节、字符串列表或 IBuffers 的类似方法.

While all the above should work - they were written before the FileIO class became available in WinRT, which simplifies most of the common scenarios that the above solution solves since you can now just call await FileIO.WriteTextAsync(file, contents) to write text into file and there are also similar methods to read, write or append strings, bytes, lists of strings or IBuffers.

这篇关于如何在 Windows 8 中使用 StreamWriter 写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Windows 8 中使用 StreamWriter 写入文件?

基础教程推荐