I am developing a client in C#. The server was developed by other who used C++ MFC, so I can´t change it. The server can only accept string data as CString (UTF8). Note: before I ask this question I have searched and read many threads, eg. thread1, thread2, thread3, etc. But they talk about conversion in C++ project or C++ context (from CString to other or from C++ String to CString, etc.), also they are not in C#.
Please help by giving me a sample code or point me the link. Thank you in advance.
Below is my sample code. It is a C# console application:
class Program
{
static void Main(string[] args)
{
String strHello = "Hello in C# String"; // immutable
// How to convert ito MFC CString equivalent? CString is mutable.
}
}
Added information (1):
The thread "Convert String^ in c# to CString in c++" is from C++ point of view (with c++ code) and not from C# pov like mine. I have only access to my client, which is written in C#. I don't have access to server code which is written in C++, so I can't change anything on server code / C++ code.
I send the data through TCP. The connection is established successfully. On server side the receiver (OnReceiveData) uses CString as parameter. Following is my send data code (after using the answer from Agent Ron). Still it doesn't work, means: server still ignores the data.
tcpClient = new TcpClient(hostname, port); Byte[] data = Encoding.UTF8.GetBytes(message); NetworkStream stream = _client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); writer.AutoFlush = false; writer.Write(data.Length); writer.Write(message); writer.Flush();
Added information (2):
Finally I can contact the developer of the server. He won't tell me the code of server, but only gives me the code fragment of his C++ client and he said it works with his server.
int XmlClient::SendLine( const CString& strSend )
{
char* source = CConversion::TcharToChar( strSend ); // UTF8 conversion
int length = strlen( source );
char* tmp = new char[length+3];
memcpy_s( tmp, length+3, source, length );
tmp[ length ] = '\0';
strcat_s( tmp, length+3, "\r\n" );
Send( tmp, length +2 );
delete[] tmp;
delete[] source;
return 0;
}