我创建了一个可序列化的类并添加了一些对象。 现在我想要在单击按钮时创建一个xml文件(基于该类),所以我这样做了:
private void Button1_Clicked(object sender, EventArgs e)
{
string fileName = "Data.xml";
MySerializableClass msc = new MySerializableClass();
XmlSerializer serializer = new XmlSerializer(typeof(MySerializableClass));
StreamWriter sw = new StreamWriter(fileName, Encoding.UTF8); //'filename' is underlined
serializer.Serialize(sw, msc);
sw.Close(); //'Close' is underlined
//'StreamWriter' does not contain a definition for 'Close' [...]
}
不幸的是我收到以下错误:无法 将 从 'String' 转换为 'System.IO.Stream'。这是什么意思?我不明白为什么编码到UTF8不起作用。不使用编码会给我带来同样的错误。
答案 0 :(得分:4)
streamwriter构造函数参数错误..
string fileName = "your file path";
using(FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
{
using (StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8))
{
MySerializableClass msc = new MySerializableClass();
XmlSerializer serializer = new XmlSerializer(typeof(MySerializableClass));
serializer.Serialize(sw, msc);
}
}
如果你想没有FileStream,请使用这个构造函数.StreamWriter(字符串路径,bool追加,编码编码)
string fileName = "your file path";
using (StreamWriter sw = new StreamWriter(fileName, true, Encoding.UTF8))
{
MySerializableClass msc = new MySerializableClass();
XmlSerializer serializer = new XmlSerializer(typeof(MySerializableClass));
serializer.Serialize(sw, msc);
}
答案 1 :(得分:1)
请参阅StreamWriter
的文档。 https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx
尝试此重载StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
或者你需要从" data.xml"创建一个Stream。文件,而不仅仅是传递文件名。