【问题标题】:Click button, open xml file, display data to textbox单击按钮,打开 xml 文件,将数据显示到文本框
【发布时间】:2018-07-26 02:43:47
【问题描述】:

我在我的 Windows 窗体应用程序中单击一个按钮,它会打开一个文件打开框。我单击要打开的 xml 文件,并且希望数据填充 Windows 窗体中的文本字段,但我得到 System.ArgumentException: 'Illegal characters in path。 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;
    }
}

【问题讨论】:

    标签: c# xml winforms


    【解决方案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;
            }
        }
    }
    

    我冒昧地在 FileStream 周围添加了一个 using,以便在您完成读取后正确处理它(否则 C# 将保持文件打开)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多