C# 单击按钮,打开xml文件,将数据显示到文本框
我在windows窗体应用程序中单击一个按钮,它会打开一个文件打开框。我单击要打开的xml文件,并希望数据填充windows窗体中的文本字段,但我得到System.ArgumentException:“路径中的非法字符。”代码的FileStream行出现错误C# 单击按钮,打开xml文件,将数据显示到文本框,c#,xml,winforms,C#,Xml,Winforms,我在windows窗体应用程序中单击一个按钮,它会打开一个文件打开框。我单击要打开的xml文件,并希望数据填充windows窗体中的文本字段,但我得到System.ArgumentException:“路径中的非法字符。”代码的FileStream行出现错误 private void button2_Click(object sender, EventArgs e) { // On click Open the file if (openFileDialog1.ShowDialo
private void button2_Click(object sender, EventArgs e)
{
// On click Open the file
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
XmlSerializer serializer = new XmlSerializer(typeof(ContactLead));
// Save file contents to variable
var fileResult = sr.ReadToEnd();
FileStream myFileStream = new FileStream(fileResult, FileMode.Open, FileAccess.Read, FileShare.Read);
ContactLead contactLead = (ContactLead)serializer.Deserialize(myFileStream);
this.textboxFirstName.Text = contactLead.firstname;
this.textboxLastName.Text = contactLead.lastname;
this.textboxEmail.Text = contactLead.email;
}
}
这就是你的问题:
var fileResult = sr.ReadToEnd();
FileStream myFileStream = new FileStream(fileResult, FileMode.Open, FileAccess.Read, FileShare.Read);
您正在读取一个文件的内容,然后将该文件的内容用作文件流的文件名。当然,该文件的XML内容在Windows或任何操作系统上都不是有效的文件名
我怀疑你真的只是想这么做:
private void button2_Click(object sender, EventArgs e)
{
// On click Open the file
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// open the file for reading
using (FileStream myFileStream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
XmlSerializer serializer = new XmlSerializer(typeof(ContactLead));
// deserialize the contact from the open file stream
ContactLead contactLead = (ContactLead)serializer.Deserialize(myFileStream);
this.textboxFirstName.Text = contactLead.firstname;
this.textboxLastName.Text = contactLead.lastname;
this.textboxEmail.Text = contactLead.email;
}
}
}
我已经在文件流中添加了一个using,这样在您读取完文件流后,它就会被正确地处理掉,否则C将保持文件的打开状态