0

I am trying write into text file from textBox in VC++ but written data in file is not right and also every time is different.

DWORD wmWritten;
textBox1->Text = "7.5";

array<Char>^ char_array1 = textBox1->Text->ToCharArray();

HANDLE hFile = CreateFile(L"C:\\MyData\\Performance\\info.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

BOOL bErrorFlag = WriteFile(hFile, &char_array1, (DWORD)(sizeof(char_array1)), &wmWritten, NULL);

Result: Η-

What is wrong?

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Is array^ char_array1 = textBox1->Text->ToCharArray(); is unmanaged type? this still not working with wrong 2 argument. Even casting to unsigned char does not help. array^ char_array1 = textBox1->Text->ToCharArray(); System::IO::File::WriteAllBytes(path, char_array1); – user3476707 Feb 06 '15 at 01:08

1 Answers1

0

@Alex said:

Don't mix managed and unmanaged types if not necessary

And I couldn't agree more. Managed classes are .NET classes and are taken care of by garbage collection, etc. Unmanaged, or native classes are traditional C++ classes where you must manage all the memory.

In this case, you can do everything using managed code. Browse through the C# webpages on how to output to a file, and then just write the corresponding code in C++/CLI.

For example, this link here:

https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-2

Is something that I found by googling "C# File IO". You can click the tabs there to see the code snippet in C# or in C++ (which means C++ CLI here). Basically, you want this:

String^ path = "c:\\temp\\MyTest.txt";
if (  !File::Exists( path ) )
 {

   // Create a file to write to.
   StreamWriter^ sw = File::CreateText( path );
   try
   {
      //sw->WriteLine( "Hello" );
      //sw->WriteLine( "And" );
      //sw->WriteLine( "Welcome" );
      sw->Write(textBox1->Text);
   }
   finally
   {
      if ( sw )
               delete (IDisposable^)(sw);
   }
}
dan-O
  • 354
  • 1
  • 10