Search code examples
c++-cliopenfiledialog

Setting openFileDialog to variable string


I am trying to create a small GUI that will rename a file (eventually a batch of files). I am using C++ and Windows user (Visual Studio Community 2015).

I have a btnSelectFiles button with which I want to open a file selection GUI.

I am trying to use openFileDialog but am struggling to set the file name to a string variable.

The code I am using:

public:
void btnSelectFiles_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
{
    IO::Stream^ myStream;
    OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;

    openFileDialog1->InitialDirectory = "c:\\";
    openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    openFileDialog1->FilterIndex = 2;
    openFileDialog1->RestoreDirectory = true;

    if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
    {
        if ((myStream = openFileDialog1->OpenFile()) != nullptr)
        {
            // Insert code to read the stream here.
            myStream->Close();
        }
    }

    /*String test = openFileDialog1;*/
}

One of my many tries was to use:

String test = openFileDialog1

I also tried:

String test = openFileDialog1.FileName 

But received an expression must have class type error.

Please can someone help me solve this and thus help my understanding on the matter. The book I have picked up does not cover this and I have struggled to find help online.


Solution

  • Since you are using c++/CLI ( rather than C++ ) you must write

    String^ test = new String( openFileDialog1.FileName );