Search code examples
c++-cli

How to write a variable in to file in C++/CLI?


I have a program in C++/CLI. I need to write my text and variable to file.

My code:

String^ MyVariable;
MyVariable = folderBrowserDialog1->SelectedPath // C://User/Users

std::ofstream out;
out.open("hello.txt");
if (out.is_open())
{
  out << "Variable: " << MyVariable << std::endl; // ERROR
}
out.close();

How to fix error?


Solution

  • C++/CLI is a different language than C++.
    It actually belong to the .NET family of languages and is meant to bridge .NET to native c++ code.

    You cannot use std::ofstream (which is a native C++ class) directly with System::String (which is a C++/CLI i.e. .NET class).

    You have 2 options:

    1. Convert the System::String (.NET) to std::string (native C++). This is demonstrated here. After the conversion you can write it to the file using std::ofstream as you attempted.

    2. Use .NET APIs for writing the file, for example with FileStream and StreamWriter, as demonstrated below:

      System::String^ MyVariable = gcnew System::String("abc");
      
      System::IO::FileStream^ fs = System::IO::File::Create("hello.txt");
      System::IO::StreamWriter^ sw = gcnew System::IO::StreamWriter(fs);
      
      sw->WriteLine("Variable: " + MyVariable);
      
      sw->Close();
      

      The content of the file will be:

      Variable: abc