Converting byte array to Unicode string in C#

J

Jay

Hi,
I am working on a project in which i am sending some data through
IrDA.(Infrared communication).

I have a C++ application on desktop PC. I am sending a character array
using send function.

the code looks like this
void doTransfer (char szUsrName[], char szPassWd[], int Proto, int
Direction,
char szHost[], char szUploadFile[], char szDownloadFile[])
{
SOCKET sock; // Socket bound to the server
DEVICELIST devList; // Device list
WSADATA wsdata;
SOCKADDR_IRDA address = {AF_IRDA, 0, 0, 0, 0, "IrDAFtp"};
TCHAR szError[100]; // Error message string
TCHAR szClientW[100]; // Unicode string
//TCHAR szAllInputsW[100]; // Unicode string
char szClientA[100]; // ASCII string
char szAllInputs[300];
//char szServerA[100]; // ASCII string
int iCount = 0, index = 0, iReturn, iTotStrLen;
int iDevListLen = sizeof (devList);
LPSTR pPtr;

WSAStartup(MAKEWORD(1,1), &wsdata);

if ((sock = socket (AF_IRDA, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Allocating socket failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return ;
}

// Initialize the number of devices to zero.
devList.numDevice = 0;

while ( (devList.numDevice == 0) && (iCount <= NUMRETYR))
{
// Retrieve the socket option.
if (getsockopt (sock, SOL_IRLMP, IRLMP_ENUMDEVICES,
(char *)&devList, &iDevListLen) == SOCKET_ERROR)
{
wsprintf (szError, TEXT("Server could not be located, getsockopt")
TEXT(" failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (sock);
return ;
}
iCount++;

// Wait one second before retrying.
Sleep (1000);
}
if (iCount > NUMRETYR)
{
MessageBox (NULL, TEXT ("Server could not be located!"),
TEXT ("Error"), MB_OK);
closesocket (sock);
return ;
}
// Get the server socket address.
for (index = 0; index <= 3; index++)
{
address.irdaDeviceID[index] = devList.Device[0].irdaDeviceID[index];
}

// Establish a connection to the socket.
if (connect (sock, (struct sockaddr *)&address,
sizeof (SOCKADDR_IRDA)) == SOCKET_ERROR)
{
wsprintf (szError,
TEXT("Connecting to the server failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (sock);
return ;
}

strcpy(szAllInputs, szUsrName);
strcat(szAllInputs, ",");
strcat(szAllInputs, szPassWd);
strcat(szAllInputs, ",");

if (Proto == 0)
strcat(szAllInputs, "0");
else
strcat(szAllInputs, "1");
strcat(szAllInputs, ",");

if (Direction == 0)
strcat(szAllInputs, "0");
else
strcat(szAllInputs, "1");

strcat(szAllInputs, ",");
strcat(szAllInputs, szHost);
strcat(szAllInputs, ",");
strcat(szAllInputs, szUploadFile);
strcat(szAllInputs, ",");
strcat(szAllInputs, szDownloadFile);

iTotStrLen = strlen(szAllInputs);

pPtr = (LPSTR)szAllInputs;
FILE *fp = fopen("File1.txt","w+");
fprintf(fp,"%s",szDownloadFile);
fclose(fp);

// Send a string from the client socket to the server socket.
if (send (sock, pPtr, iTotStrLen + 1, 0) == SOCKET_ERROR)
{
wsprintf (szError, TEXT("Sending data to the server failed. Error:
%d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
}

// Receive data from the server socket.
iReturn = recv (sock, szClientA, sizeof (szClientA), 0);

// Check if there is any data received. If there is, display it.
if (iReturn == SOCKET_ERROR)
{
wsprintf (szError, TEXT("No data is received, recv failed.")
TEXT(" Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Client"), MB_OK);
}
else if (iReturn == 0)
{
MessageBox (NULL, TEXT("Finished receiving data"), TEXT("Client"),
MB_OK);
}
else
{
// Convert the ASCII string to a Unicode string
szClientA[99] = 0;
MultiByteToWideChar(CP_ACP, 0, szClientA, -1,
szClientW,
sizeof(szClientW)/sizeof(szClientW[0]));
// Display the string received from the server.
MessageBox (NULL, szClientW, TEXT("Received From Server"), MB_OK);
}

// Close the socket.
closesocket (sock);
return;
}

On a mobile device I am using a C# based application which receives
this data through Infrared socket. the code for C# :

public ReceiveData()
{
// Create a connection, with the IrDAEndPoint class,
// for the selected device in the list box.
// Start listening for incoming requests from
// that device with the IrDAListener class.
try
{

irEndP = new IrDAEndPoint(irDevices[0].DeviceID,
irServiceName);
irListen = new IrDAListener(irEndP);
irListen.Start();
}
catch (SocketException exSoc)
{
MessageBox.Show("Couldn't listen on service "
+ irServiceName + ": "
+ exSoc.ErrorCode);
}


// Create a client connection for the
// service detected by the listener.
IrDAClient irClient;
try
{
irClient = irListen.AcceptIrDAClient();
}
catch (SocketException exp)
{
MessageBox.Show("Couldn't accept socket "
+ exp.ErrorCode);
return;
}


// Get the underlying stream of the client.
Stream baseStream = irClient.GetStream();

//Create buffer for reading the file.
byte[] buffer = new byte[buffersize];

// Read the stream of data, which contains
// the data from the remote device, until
// there are no more bytes to read.
int numRead = baseStream.Read(buffer, 0, buffer.Length);

UTF8Encoding UTF8enc = new UTF8Encoding();

try
{
// char[] ch = UTF8enc.GetChars(buffer, 0, buffer.Length
- 1);
string str = UTF8enc.GetString(buffer, 0,
buffer.Length);


ASCIIEncoding encoding = new ASCIIEncoding();
//UnicodeEncoding encoding = new UnicodeEncoding();
//string str = encoding.GetString(buffer, 0,
buffer.Length);


string[] split = str.Split(',');
string sUserName = split[0];
string sPassword = split[1];
string sProto = split[2];
string sDownloadDirection = split[3];
string sHost = split[4];
string sUploadFile = split[5];
string sDownloadFile = split[6];
string sFile = sDownloadFile.Trim();
stream.WriteLine(sFile);

stream.WriteLine(sFile);


stream.Flush();

doTransfer(sUserName, sPassword, sProto,
sDownloadDirection, sHost, sFile, sFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
baseStream.Close();

irListen.Stop();
irClient.Close();


}

}

I am passing sFile string to FileInfo class constructor but it throws
ArgumentException.

Basically I am converting a byte array containing ASSCII values to
unicode string.
What is the reason it is throwing ArgumentException.

Thanks
Jayshri
 
F

Fabien

Hi,

I don't see where you create your FileInfo object?
I think you must use FileInfo with the StreamWriter object as below :
FileInfo fi = new FileInfo(path);
if (!fi.Exists)
{
//Create a file to write to.
StreamWriter sw = fi.CreateText())
sw.WriteLine("Hello");
}

BR

Fabien Decret

ADENEO (ADESET)
http://www.adeneo.adetelgroup.com/

Jay a écrit :
Hi,
I am working on a project in which i am sending some data through
IrDA.(Infrared communication).

I have a C++ application on desktop PC. I am sending a character array
using send function.

the code looks like this
void doTransfer (char szUsrName[], char szPassWd[], int Proto, int
Direction,
char szHost[], char szUploadFile[], char szDownloadFile[])
{
SOCKET sock; // Socket bound to the server
DEVICELIST devList; // Device list
WSADATA wsdata;
SOCKADDR_IRDA address = {AF_IRDA, 0, 0, 0, 0, "IrDAFtp"};
TCHAR szError[100]; // Error message string
TCHAR szClientW[100]; // Unicode string
//TCHAR szAllInputsW[100]; // Unicode string
char szClientA[100]; // ASCII string
char szAllInputs[300];
//char szServerA[100]; // ASCII string
int iCount = 0, index = 0, iReturn, iTotStrLen;
int iDevListLen = sizeof (devList);
LPSTR pPtr;

WSAStartup(MAKEWORD(1,1), &wsdata);

if ((sock = socket (AF_IRDA, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Allocating socket failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return ;
}

// Initialize the number of devices to zero.
devList.numDevice = 0;

while ( (devList.numDevice == 0) && (iCount <= NUMRETYR))
{
// Retrieve the socket option.
if (getsockopt (sock, SOL_IRLMP, IRLMP_ENUMDEVICES,
(char *)&devList, &iDevListLen) == SOCKET_ERROR)
{
wsprintf (szError, TEXT("Server could not be located, getsockopt")
TEXT(" failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (sock);
return ;
}
iCount++;

// Wait one second before retrying.
Sleep (1000);
}
if (iCount > NUMRETYR)
{
MessageBox (NULL, TEXT ("Server could not be located!"),
TEXT ("Error"), MB_OK);
closesocket (sock);
return ;
}
// Get the server socket address.
for (index = 0; index <= 3; index++)
{
address.irdaDeviceID[index] = devList.Device[0].irdaDeviceID[index];
}

// Establish a connection to the socket.
if (connect (sock, (struct sockaddr *)&address,
sizeof (SOCKADDR_IRDA)) == SOCKET_ERROR)
{
wsprintf (szError,
TEXT("Connecting to the server failed. Error: %d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (sock);
return ;
}

strcpy(szAllInputs, szUsrName);
strcat(szAllInputs, ",");
strcat(szAllInputs, szPassWd);
strcat(szAllInputs, ",");

if (Proto == 0)
strcat(szAllInputs, "0");
else
strcat(szAllInputs, "1");
strcat(szAllInputs, ",");

if (Direction == 0)
strcat(szAllInputs, "0");
else
strcat(szAllInputs, "1");

strcat(szAllInputs, ",");
strcat(szAllInputs, szHost);
strcat(szAllInputs, ",");
strcat(szAllInputs, szUploadFile);
strcat(szAllInputs, ",");
strcat(szAllInputs, szDownloadFile);

iTotStrLen = strlen(szAllInputs);

pPtr = (LPSTR)szAllInputs;
FILE *fp = fopen("File1.txt","w+");
fprintf(fp,"%s",szDownloadFile);
fclose(fp);

// Send a string from the client socket to the server socket.
if (send (sock, pPtr, iTotStrLen + 1, 0) == SOCKET_ERROR)
{
wsprintf (szError, TEXT("Sending data to the server failed. Error:
%d"),
WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
}

// Receive data from the server socket.
iReturn = recv (sock, szClientA, sizeof (szClientA), 0);

// Check if there is any data received. If there is, display it.
if (iReturn == SOCKET_ERROR)
{
wsprintf (szError, TEXT("No data is received, recv failed.")
TEXT(" Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Client"), MB_OK);
}
else if (iReturn == 0)
{
MessageBox (NULL, TEXT("Finished receiving data"), TEXT("Client"),
MB_OK);
}
else
{
// Convert the ASCII string to a Unicode string
szClientA[99] = 0;
MultiByteToWideChar(CP_ACP, 0, szClientA, -1,
szClientW,
sizeof(szClientW)/sizeof(szClientW[0]));
// Display the string received from the server.
MessageBox (NULL, szClientW, TEXT("Received From Server"), MB_OK);
}

// Close the socket.
closesocket (sock);
return;
}

On a mobile device I am using a C# based application which receives
this data through Infrared socket. the code for C# :

public ReceiveData()
{
// Create a connection, with the IrDAEndPoint class,
// for the selected device in the list box.
// Start listening for incoming requests from
// that device with the IrDAListener class.
try
{

irEndP = new IrDAEndPoint(irDevices[0].DeviceID,
irServiceName);
irListen = new IrDAListener(irEndP);
irListen.Start();
}
catch (SocketException exSoc)
{
MessageBox.Show("Couldn't listen on service "
+ irServiceName + ": "
+ exSoc.ErrorCode);
}


// Create a client connection for the
// service detected by the listener.
IrDAClient irClient;
try
{
irClient = irListen.AcceptIrDAClient();
}
catch (SocketException exp)
{
MessageBox.Show("Couldn't accept socket "
+ exp.ErrorCode);
return;
}


// Get the underlying stream of the client.
Stream baseStream = irClient.GetStream();

//Create buffer for reading the file.
byte[] buffer = new byte[buffersize];

// Read the stream of data, which contains
// the data from the remote device, until
// there are no more bytes to read.
int numRead = baseStream.Read(buffer, 0, buffer.Length);

UTF8Encoding UTF8enc = new UTF8Encoding();

try
{
// char[] ch = UTF8enc.GetChars(buffer, 0, buffer.Length
- 1);
string str = UTF8enc.GetString(buffer, 0,
buffer.Length);


ASCIIEncoding encoding = new ASCIIEncoding();
//UnicodeEncoding encoding = new UnicodeEncoding();
//string str = encoding.GetString(buffer, 0,
buffer.Length);


string[] split = str.Split(',');
string sUserName = split[0];
string sPassword = split[1];
string sProto = split[2];
string sDownloadDirection = split[3];
string sHost = split[4];
string sUploadFile = split[5];
string sDownloadFile = split[6];
string sFile = sDownloadFile.Trim();
stream.WriteLine(sFile);

stream.WriteLine(sFile);


stream.Flush();

doTransfer(sUserName, sPassword, sProto,
sDownloadDirection, sHost, sFile, sFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
baseStream.Close();

irListen.Stop();
irClient.Close();


}

}

I am passing sFile string to FileInfo class constructor but it throws
ArgumentException.

Basically I am converting a byte array containing ASSCII values to
unicode string.
What is the reason it is throwing ArgumentException.

Thanks
Jayshri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top