-4

I am writing a simple ftp client with c#.
I am not pro in c#. Is there any way to convert string to byte[] and write it to the socket?
for example for introducing username this is the socket content:

5553455220736f726f7573680d0a

and ASCII equivalent is:

USER soroush

I want a method to convert string. Something like this:

public byte[] getByte(string str)
{
    byte[] ret;
    //some code here
    return ret;
}
Soroush Khosravi
  • 887
  • 2
  • 11
  • 30
  • 1
    duplicate http://stackoverflow.com/questions/6891438/convert-string-to-byte-array – J.K Aug 13 '12 at 07:29
  • 1
    Why I got -1 vote down ? – Soroush Khosravi Aug 13 '12 at 07:29
  • 2
    Other duplicates: http://stackoverflow.com/questions/5056336/c-sharp-byte-byte-array-to-unicode-string http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp http://stackoverflow.com/questions/4318693/string-to-byte-and-vice-versa -1 for "does not show any research effort". – Bridge Aug 13 '12 at 07:29

2 Answers2

5

Try

byte[] array = Encoding.ASCII.GetBytes(input);

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
J.K
  • 2,290
  • 1
  • 18
  • 29
4
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    Encoding encoding = Encoding.UTF8; //or below line
    //System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}

and

// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
Encoding enc = Encoding.UTF8; //or below line 
//System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263