OpenFileDialog仅读取第一个文件 [英] OpenFileDialog reads only the first file

查看:102
本文介绍了OpenFileDialog仅读取第一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码打开多个XML文件并读取文件的内容,但是它不起作用.

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

出于测试目的,我创建了两个xml文件.

For testing purposes, I created two xml files.

  • file1.xml(其内容为"string1")
  • file2.xml(其内容为"string2")

当我打开对话框并选择两个文件时,我会收到四则消息.

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

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

即使OpenFileDialog正确读取了文件名,我也无法读取第二个文件.它只读取第一个文件.因此,我猜测问题与StreamReader有关,而不与OpenFileDialog有关.我在做什么错了?

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?

推荐答案

您在每次迭代中都使用OpenFD.OpenFile()

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

打开用户选择的文件,该文件由 FileName 属性指定.

哪个依次:

只能是一个选定文件的名称.

请改为使用循环中的file变量,并使用 StreamReader接受字符串的构造器:

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

这篇关于OpenFileDialog仅读取第一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆