我在Windows窗体应用程序中单击一个按钮,它会打开一个文件打开框。我单击要打开的xml文件,并希望数据填充Windows窗体中的文本字段,但出现System.ArgumentException:“路径中包含非法字符”。错误在FileStream代码行上。
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;
}
}
答案 0 :(得分:1)
这是您的问题:
var fileResult = sr.ReadToEnd();
FileStream myFileStream = new FileStream(fileResult, FileMode.Open, FileAccess.Read, FileShare.Read);
您正在读取一个文件的内容,然后将该文件的内容用作FileStream
的文件名。当然,该文件的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
周围添加了FileStream
,以便在您完成对它的读取之后将其正确处理(否则C#将使文件保持打开状态。) / p>