OpenFileDialog reads only the first file

被刻印的时光 ゝ 提交于 2019-12-12 01:51:37

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/31186376/openfiledialog-reads-only-the-first-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!