0

I click a button in my windows form app, and it opens a file open box. I click the xml file I want to open and I want the data to populate the text fields in my windows form, but I get System.ArgumentException: 'Illegal characters in path.' error on the FileStream line of code.

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;
    }
}

1 Answer 1

1

This is your problem:

var fileResult = sr.ReadToEnd();
FileStream myFileStream = new FileStream(fileResult, FileMode.Open, FileAccess.Read, FileShare.Read);

You're reading the contents of one file, and then using the contents of that file as the filename for your FileStream. Of course the XML content of that file isn't a valid filename on Windows, or any operating system.

I suspect you really just want to do this:

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;
        }
    }
}

I've taken the liberty of adding a using around the FileStream so that it is properly disposed of after you're done reading from it (otherwise C# will keep the file open).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.