如何将XML Dialog.FileName传递到StreamReader进行反序列化
本文关键字:StreamReader 反序列化 XML Dialog FileName | 更新日期: 2023-09-27 17:58:53
因此,目前在我的WPF项目中,我让用户浏览一个XML文件,然后我想反序列化该XML文件并在DataGrid中显示数据。
我确信我的反序列化函数有效。然而,我目前只将其设置为反序列化一个XML文件,如下所示:
public static void DeSerializationXML()
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "lot_information";
xRoot.IsNullable = false;
// Create an instance of analytes class.
LotInformation[] lotinfo;
// Create an instance of stream writer.
TextReader txtReader = new StreamReader(@"C:'~'lot-123456.xml");
// Create and instance of XmlSerializer class.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(LotInformation[]), xRoot);
// DeSerialize from the StreamReader
lotinfo = (LotInformation[])xmlSerializer.Deserialize(txtReader);
// Close the stream reader
txtReader.Close();
Console.ReadLine();
}
在另一个功能中,我有以下功能,允许用户浏览文件并上传:
private void ChangeLotFilePath()
{
OpenFileDialog Dialog = new OpenFileDialog();
Dialog.Filter = "XML files (*.xml)|*.xml";
Dialog.ShowDialog();
if (!String.IsNullOrEmpty(Dialog.FileName))
{
LotFileCreationDirectory = Dialog.FileName.ToString();
}
DeSerializationXML();
}
现在我想知道,如何将Dialog.FileName.ToString()传递给StreamReader,以便它识别用户选择的文件路径?
为什么不将路径作为参数?
public static void DeSerializationXML(string path)
{
...
TextReader txtReader = new StreamReader(path);
}
private void ChangeLotFilePath()
{
using (var dialog = new OpenFileDialog()) {
dialog.Filter = "XML files (*.xml) | *.xml";
if (dialog.ShowDialog() == DialogResult.OK) {
DeserializationXML(dialog.FileName);
}
}
}