How write a file using StreamWriter in Windows 8?(如何在 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 写入文件?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01