问题描述
我正在使用以下代码打开多个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:
哪个依次:
请改为使用循环中的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仅读取第一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!