C# 如何在 Windows 8 中使用 StreamWriter 写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10290820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How write a file using StreamWriter in Windows 8?
提问by Jorge Monta?o
I'm having trouble when creating a StreamWriterobject 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?.
我StreamWriter在 windows-8 中创建对象时遇到问题,通常我只是创建一个实例,只传递一个字符串作为参数,但在 Windows 8 中我收到一个错误,表明它应该接收一个流,但我注意到 Stream是一个抽象类,有人知道如何编写 xml 文件的代码吗?顺便说一句,我使用 .xml 是因为我想保存序列化对象,或者有人知道如何将序列化对象保存到文件中视窗 8?。
Any ideas?
有任何想法吗?
Currently using Windows 8 Consumer Preview
目前使用的是 Windows 8 Consumer Preview
Code:
代码:
StreamWriter sw = new StreamWriter("person.xml");
StreamWriter sw = new StreamWriter("person.xml");
Error:
错误:
The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream)' has some invalid arguments
The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream)' has some invalid arguments
采纳答案by Filip Skakun
Instead of StreamWriter you would use something like this:
而不是 StreamWriter 你会使用这样的东西:
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();
}
}
You can look at the StringIOExtensionsclass in the WinRTXamlToolkitlibrary for sample use.
您可以查看WinRTXamlToolkit库中的StringIOExtensions类以供示例使用。
EDIT*
编辑*
While all the above should work - they were written before the FileIOclass 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.
虽然上述所有内容都应该有效 - 它们是在FileIO类在 WinRT 中可用之前编写的,这简化了上述解决方案解决的大多数常见场景,因为您现在只需调用await FileIO.WriteTextAsync(file, contents)将文本写入文件,并且还有类似的方法来读取,写入或附加字符串、字节、字符串列表或IBuffers.
回答by Shivam cv
You can create a common static method which you can use through out application like this
您可以创建一个通用的静态方法,您可以像这样在整个应用程序中使用它
private async Task<T> ReadXml<T>(StorageFile xmldata)
{
XmlSerializer xmlser = new XmlSerializer(typeof(List<myclass>));
T data;
using (var strm = await xmldata.OpenStreamForReadAsync())
{
TextReader Reader = new StreamReader(strm);
data = (T)xmlser.Deserialize(Reader);
}
return data;
}
private async Task writeXml<T>(T Data, StorageFile file)
{
try
{
StringWriter sw = new StringWriter();
XmlSerializer xmlser = new XmlSerializer(typeof(T));
xmlser.Serialize(sw, Data);
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteString(sw.ToString());
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
catch (Exception e)
{
throw new NotImplementedException(e.Message.ToString());
}
}
to write xml simply use
写xml简单地使用
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("data.xml",CreationCollisionOption.ReplaceExisting);
await writeXml(Data,file);
and to read xml use
并阅读xml使用
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.xml");
Data = await ReadXml<List<myclass>>(file);

