Search code examples
c++-cli

How do I read multiple files after click opened in OpenFileDialog?


I have set a multiselect function in my code to allow me to open multiple files which is in ".txt" forms. And here is the problem, how am I going to read all these selected files after it opened through OpenFileDialog? The following codes and at the "for each" line, when I use System::Diagnostics::Debug, it shows only the data from a file, while data of other files were missing. How should I modify the code after the "for each"? Can anyone provide some suggestions or advice? The files selected are as 1_1.txt, 2_1.txt, 3_1.txt. Appreciate your reply and Thanks in advance.

Here is my written code,

Stream^ myStream;  
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;  
openFileDialog1->InitialDirectory = "c:\\";  
openFileDialog1->Title = "open captured file";  
openFileDialog1->Filter = "CP files (*.cp)|*.cp|All files (*.*)|*.*|txt files (*.txt)|*.txt";  
openFileDialog1->FilterIndex = 2;  
openFileDialog1->Multiselect = true;  

if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )  
{  
  array<String^>^ lines = System::IO::File::ReadAllLines(openFileDialog1->FileName);  
  for each (String^ line in lines) {  
    //?????  
    System::Diagnostics::Debug::WriteLine("",line);  
  }  
}  

Solution

  • You need to look at the OpenFileDialog.FileNames property if you allow multiple files to be selected:

    if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )  
    {  
      for each (String^ file in openFileDialog1->FileNames) 
      {  
        array<String^>^ lines = System::IO::File::ReadAllLines(file);  
        for each (String^ line in lines) 
        {  
          System::Diagnostics::Debug::WriteLine("",line);  
        }
      }  
    }