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.
When I open the dialog and select the two files, I get four messages.
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?
You're using OpenFD.OpenFile()
in each iteration, which:
Opens the file selected by the user, [...] specified by the FileName property.
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());
}