Reputation: 12027
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?
Upvotes: 0
Views: 416
Reputation: 1765
This line is opening the file from the OpenFileDialog:
System.IO.Stream fileStream = OpenFD.OpenFile();
But there's no specification for which file. You need a way to distinguish which file you're opening. I would get rid of that line all together and just use the string file you have in the loop.
System.IO.StreamReader streamReader = new System.IO.StreamReader(file);
Upvotes: 3
Reputation: 151584
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());
}
Upvotes: 3