Search code examples
c#streamreaderopenfiledialog

OpenFileDialog reads only the first file


I'm using the following code to open multiple XML files and read the contents of the files but it doesn't work.

OpenFD.Filter = "XML Files (*.xml)|*.xml";
OpenFD.Multiselect = true;

if (OpenFD.ShowDialog() == DialogResult.OK)
{
    foreach (string file in OpenFD.FileNames)
    {
        MessageBox.Show(file);

        System.IO.Stream fileStream = OpenFD.OpenFile();
        System.IO.StreamReader streamReader = new System.IO.StreamReader(fileStream);
        using (streamReader)
        {
            MessageBox.Show(streamReader.ReadToEnd());
        }
        fileStream.Close();
    }
}

For testing purposes, I created two xml files.

  • file1.xml (its content is "string1")
  • file2.xml (its content is "string2")

When I open the dialog and select the two files, I get four messages.

  • file1.xml
  • string1
  • file2.xml
  • string1

Even though the OpenFileDialog reads the file names correctly, I can't get to read the second file. It only reads the first file. So I'm guessing the problem is related to StreamReader, not to OpenFileDialog. What am I doing wrong?


Solution

  • You're using OpenFD.OpenFile() in each iteration, which:

    Opens the file selected by the user, [...] specified by the FileName property.

    Which in turn:

    can only be the name of one selected file.

    Use the file variable from your loop instead, and the StreamReader constructor that accepts a string:

    using (var streamReader = new System.IO.StreamReader(file))
    {
        MessageBox.Show(streamReader.ReadToEnd());
    }